Java日期格式转换 - 月份错误

9

我在Java中转换日期时遇到了问题,不知道哪里出错了...

    String dateStr = "2011-12-15";
    String fromFormat = "yyyy-mm-dd";
    String toFormat = "dd MMMM yyyy";

    try {
        DateFormat fromFormatter = new SimpleDateFormat(fromFormat);
        Date date = (Date) fromFormatter.parse(dateStr);

        DateFormat toformatter = new SimpleDateFormat(toFormat);
        String result = toformatter.format(date);

    } catch (ParseException e) {
        e.printStackTrace();
    }

输入的日期是2011年12月15日,我期望得到的结果是“2011年12月15日”,但实际上我得到的是“2011年1月15日”。

我哪里出错了?

8个回答

35

您的fromFormat使用分钟,而应该使用月份。

String fromFormat = "yyyy-MM-dd";

6

2

查看SimpleDateFormat的javadoc,了解m代表什么。它代表分钟,而不是你想象中的月份。


2
 String fromFormat = "yyyy-MM-dd"; 

2

格式应为:

String fromFormat = "yyyy-MM-dd"

1

SimpleDateFormat 中的 m 表示分钟,而 M 表示月份。因此,您的第一个格式应该是 yyyy-MM-dd


我喜欢 Stack Overflow 的一件事情是问题得到了非常快速的回答。当我正在回答一个问题时,仅仅1分钟内就有3个新的回答,太棒了! - ffriend

1

tl;dr

LocalDate.parse( "2011-12-15" )                            // Date-only, without time-of-day, without time zone.
.format(                                                   // Generate `String` representing value of this `LocalDate`. 
    DateTimeFormatter.ofLocalizedDate( FormatStyle.LONG )  // How long or abbreviated?
                     .withLocale(                          // Locale used in localizing the string being generated.
                         new Locale( "en" , "IN" )         // English language, India cultural norms.
                     )                                     // Returns a `DateTimeFormatter` object.
)                                                          // Returns a `String` object.

15 December 2011

java.time

已接受的答案是正确的(月份大写MM),但现在有了更好的方法。令人困扰的旧日期时间类现在已经过时,被java.time类取代。

您的输入字符串采用标准ISO 8601格式。因此,在解析时不需要指定格式模式。

LocalDate ld = LocalDate.parse( "2011-12-15" );  // Parses standard ISO 8601 format by default.
Locale l = new Locale( "en" , "IN" ) ;  // English in India.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.LONG )
                                       .withLocale( l );
String output = ld.format( f );

转储到控制台。

System.out.println( "ld.toString(): " + ld );
System.out.println( "output: " + output );

ld.toString(): 2011-12-15

output: 15 December 2011

请查看IdeOne.com上的实时代码


关于 java.time

java.time 框架是内置于 Java 8 及更高版本中的。这些类替代了老旧的遗留日期时间类,例如 java.util.DateCalendarSimpleDateFormat

Joda-Time项目现在处于维护模式,建议迁移到java.time类。

了解更多信息,请参见Oracle教程。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

您可以直接与数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC驱动程序。无需字符串,无需java.sql.*类。

如何获取java.time类?

ThreeTen-Extra项目通过添加额外的类扩展了java.time。该项目是java.time可能未来添加的潜在试验场。您可能会在这里找到一些有用的类,例如Interval, YearWeek, YearQuarter, 以及更多


0

这可能不是你的情况,但可能会帮助到其他人。在我的情况下,在转换后,日期和月份都被设置为1。所以无论日期是什么,在转换后我都得到了1月1日,这是错误的。 经过一番努力,我发现在日期格式中我使用了YYYY而不是yyyy。当我将所有大写字母Y改为小写字母y时,它就正常工作了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接