SimpleDateFormat.format() 未返回格式正确的日期字符串

SimpleDateFormat.format() not returning correct formatted date string

我正在尝试将日期格式化为 "MMMMM yy" 格式。但是,当我 运行 代码时,它没有 return 完全格式化的日期。

这是代码

Date date = Calendar.getInstance().getTime(); // "Mon Jun 10 09:50:06 HST 2019"
SimpleDateFormat format = new SimpleDateFormat("MMMMM yy", Locale.US);
String formatDate = format.format(date); // "J 19"
System.out.println(formatDate);

假设输入的日期是 "Mon Jun 10 09:50:06 HST 2019",结果输出是 "J 19",而我希望它是 "June 19"。我觉得我在这里遗漏了一些简单的东西,但无法弄清楚是什么。

MMMMM 对应 "tiny" 月份格式。对完整的月份名称使用 four-letter MMMM 格式。

参考文献:

https://developer.android.com/reference/android/icu/text/SimpleDateFormat

http://androidxref.com/9.0.0_r3/xref/libcore/ojluni/src/main/java/java/text/SimpleDateFormat.java#1426

我试过你的代码,它按预期工作。结果我得到了 6 月 19 日。正如 Andreas 已经评论的那样,您可以在 SimpleDateFormat 中删除一个 M,因为长度超过 3 的模式字母将采用完整形式。

Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.

Text: For formatting, if the number of pattern letters is 4 or more, the full form is used; otherwise a short or abbreviated form is used if available. For parsing, both forms are accepted, independent of the number of pattern letters.

因此您的 SimpleDateFormat 模式将是:

new SimpleDateFormat("MMMM yy", Locale.US);

来自 Android Documentation for SimpleDateFormat :

Stand-Alone Month - Use one or two for the numerical month, three for the abbreviation, four for the full (wide) name, or 5 for the narrow name. With two ("LL"), the month number is zero-padded if necessary (e.g. "08").

代码应该是:

Date date = Calendar.getInstance().getTime();
SimpleDateFormat format = new SimpleDateFormat("MMMM yy", Locale.US);
String formatDate = format.format(date); 
System.out.println(formatDate);

输出:

June 19

java.time 和 ThreeTenABP

    DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMMM uu", Locale.US);
    YearMonth thisMonth = YearMonth.now(ZoneId.of("America/Louisville"));
    String formatDate = thisMonth.format(monthFormatter);
    System.out.println(formatDate);

当我运行刚才这个片段时,输出是:

June 19

我正在使用并推荐 java.time,现代 Java 日期和时间 API。您使用的 date-time 类,Calendar,尤其是 SimpleDateFormat,总是设计得很差,而且早就过时了。

问题:我可以在 Android 上使用 java.time 吗?

是的,java.time 在新旧 Android 设备上都能很好地工作。它只需要至少 Java 6.

  • 在 Java 8 和更新的 Android 设备上(从 API 级别 26)现代 API 出现 built-in.
  • 在 Java 6 和 7 中获取现代 类 的 ThreeTen Backport(ThreeTen 用于 JSR 310;请参阅底部的链接)。
  • 在(较旧的)Android 使用 ThreeTen Backport 的 Android 版本。它叫做 ThreeTenABP。并确保使用子包从 org.threeten.bp 导入日期和时间 类。

链接