How to parse a date with 24h time using joda?

How can I tell joda-time to automatically detect 24h Hour strings and parse them accordingly?

DateTimeFormat.forPattern("YYYYMMDDhhmm").parseDateTime("201410171500");

Results in:

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)

By the way, which is strange: the following works without an error:

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

Jon Skeet
people
quotationmark

You need to read the documentation for pattern characters very carefully:

  • You want yyyy rather than YYYY, as you want regular calendar years rather than year-of-era. (Not likely to be significant in Joda Time, but if you port the code to use SimpleDateFormat, YYYY would mean week-year, which you really don't want.)
  • You want HH rather than hh for 24-hour clock
  • You want dd rather than DD for day-of-month (you don't want day-of-year)

So:

DateTimeFormat.forPattern("yyyyMMddHHmm").parseDateTime("201410171500");

people

See more on this question at Stackoverflow