如何使用joda解析24小时的日期?

mem*_*und 0 java datetime jodatime

如何判断joda-time自动检测24小时字符串并相应地解析它们?

DateTimeFormat.forPattern("YYYYMMDDhhmm").parseDateTime("201410171500");
Run Code Online (Sandbox Code Playgroud)

结果是:

org.joda.time.IllegalFieldValueException: Cannot parse "201410171500": Value 50 for clockhourOfHalfday must be in the range [1,12]
    at org.joda.time.field.FieldUtils.verifyValueBounds(FieldUtils.java:234)
    at org.joda.time.field.ZeroIsMaxDateTimeField.set(ZeroIsMaxDateTimeField.java:86)
    at org.joda.time.format.DateTimeParserBucket$SavedField.set(DateTimeParserBucket.java:568)
    at org.joda.time.format.DateTimeParserBucket.computeMillis(DateTimeParserBucket.java:447)
    at org.joda.time.format.DateTimeParserBucket.computeMillis(DateTimeParserBucket.java:411)
    at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:882)
Run Code Online (Sandbox Code Playgroud)

顺便说一句,这很奇怪:以下工作没有错误:

DateTimeFormat.forPattern("YYYYMMDDHH").parseDateTime("2014101715");

Jon*_*eet 5

您需要非常仔细地阅读模式字符文档:

  • 你想要yyyy而不是YYYY,因为你想要的是常规日历年而不是年代.(在Joda Time中不太可能有重要意义,但是如果您要使用代码SimpleDateFormat,YYYY那么就意味着一周,这是您真正不想要的.)
  • 你想要HH而不是hh24小时制
  • 你想要dd而不是DD每天(你不想要一年中的一天)

所以:

DateTimeFormat.forPattern("yyyyMMddHHmm").parseDateTime("201410171500");
Run Code Online (Sandbox Code Playgroud)