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

时间:2019-06-10 19:55:17

标签: java android simpledateformat

我正在尝试将日期格式化为“ MMMMM yy”格式。但是,当我运行代码时,它不会返回完全格式化的日期。

这是代码

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"。我觉得我在这里遗漏了一些简单的东西,但无法弄清楚是什么。

4 个答案:

答案 0 :(得分:3)

答案 1 :(得分:0)

来自Android Documentation for SimpleDateFormat

  

独立月份-数字月份使用一两个,月份表示三个   缩写,全名(宽)为4,窄号为5   名称。对于两个(“ LL”),如有必要,月份号为零   (例如“ 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

答案 2 :(得分:0)

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);

我刚才运行此代码段时,输出为:

  

6月19日

我正在使用并推荐使用Java.time(现代Java日期和时间API)。您使用的日期时间类Calendar尤其是SimpleDateFormat的设计总是很差,并且已经过时了。

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

是的,java.time在较新和较旧的Android设备上均可正常运行。它只需要至少 Java 6

  • 在Java 8和更高版本以及更新的Android设备(API级别26以上)中,内置了现代API。
  • 在Java 6和7中,获得了ThreeTen反向端口,这是现代类的反向端口(JSR 310的ThreeTen;请参见底部的链接)。
  • 在(较旧的)Android上,使用Android版本的ThreeTen Backport。叫做ThreeTenABP。并确保您使用子包从org.threeten.bp导入日期和时间类。

链接

答案 3 :(得分:-1)

我已经尝试过您的代码,并且可以正常工作。结果是6月19日。正如Andreas所说,您可以在SimpleDateFormat中删除一个M,因为长度大于3的模式字母将采用完整格式。

  

月份:如果图案字母的数量为3个或更多,则月份被解释为文本;否则,它将被解释为数字。

     

文本:对于格式设置,如果图案字母的数量为4个或更多,则使用完整格式;否则,请使用简短形式或缩写形式。对于解析,两种格式都可以接受,而与模式字母的数量无关。

因此您的SimpleDateFormat模式将是:

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