You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Java的Date对象转换为带序数词后缀的日期格式(如May 15th, 2018)

在Java中将Date转换为带序数词后缀的日期字符串(如May 15th, 2018)

嗨,这个需求在生成友好的英文日期展示时确实很常见。Java 8之后推出的java.time包是处理日期时间的首选方案——相比旧的Date和SimpleDateFormat,它不仅线程安全,还能避免很多旧API的坑。下面我给你两种实用的实现方案,分别适配新老版本的Java:

Java 8+ 推荐方案

首先,我们需要把旧的java.util.Date转换成java.time.LocalDate(新API的核心类之一),然后自定义逻辑处理序数词后缀:

步骤1:转换Date到LocalDate

Date date = new Date(); // 你的目标Date对象
LocalDate localDate = date.toInstant()
                          .atZone(ZoneId.systemDefault()) // 可指定时区,比如ZoneId.of("UTC")
                          .toLocalDate();

步骤2:编写序数词后缀工具方法

这个方法会根据日期数字返回对应的st/nd/rd/th:

private static String getOrdinalSuffix(int day) {
    // 11、12、13比较特殊,统一用th
    if (day >= 11 && day <= 13) {
        return "th";
    }
    switch (day % 10) {
        case 1: return "st";
        case 2: return "nd";
        case 3: return "rd";
        default: return "th";
    }
}

步骤3:拼接成目标格式

// 获取英文全称月份(比如May)
String month = localDate.getMonth().getDisplayName(TextStyle.FULL, Locale.ENGLISH);
int day = localDate.getDayOfMonth();
int year = localDate.getYear();

// 组合成最终字符串
String formattedDate = String.format("%s %d%s, %d", month, day, getOrdinalSuffix(day), year);
// 输出示例:May 15th, 2018
System.out.println(formattedDate);

Java 7及以下兼容方案

如果还在维护老项目,只能用旧API的话,可以通过SimpleDateFormat拆分日期各部分,再加上后缀:

Date date = new Date();
// 分别格式化月份、日期、年份
SimpleDateFormat monthFormat = new SimpleDateFormat("MMMM", Locale.ENGLISH);
SimpleDateFormat dayFormat = new SimpleDateFormat("d", Locale.ENGLISH);
SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy", Locale.ENGLISH);

String month = monthFormat.format(date);
int day = Integer.parseInt(dayFormat.format(date));
int year = Integer.parseInt(yearFormat.format(date));

// 复用上面的getOrdinalSuffix方法
String formattedDate = String.format("%s %d%s, %d", month, day, getOrdinalSuffix(day), year);
System.out.println(formattedDate);

注意事项

  • Locale设置:一定要指定Locale.ENGLISH,否则如果系统默认语言不是英文,月份会显示成其他语言(比如中文的"五月")。
  • 线程安全:SimpleDateFormat是非线程安全的,在多线程环境下要么每次创建新实例,要么用ThreadLocal来封装;而java.time下的所有类都是线程安全的,这也是优先推荐新API的原因之一。

内容的提问来源于stack exchange,提问作者Deep Grewal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:03:10