Java8 DateTimeFormatter am/pm
Asked Answered
S

3

27

I am trying to parse some dates, but the DateTimeParser seems to disagree with me on what is valid

import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale

ZonedDateTime.parse("Wed Jul 16, 2016 4:38pm EDT", DateTimeFormatter.ofPattern("EEE MMM dd, yyyy hh:mma z", Locale.US))

When I try this it says

java.time.format.DateTimeParseException: Text 'Wed Jul 16, 2016 4:38pm EDT' could not be parsed at index 17

So something is wrong with the hours? When I drop one of the 'h' it gets further ( altough it should just 0-pad my hours ), but then it doesn't like the pm-stuff

ZonedDateTime.parse("Wed Jul 16, 2016 4:38pm EDT", DateTimeFormatter.ofPattern("EEE MMM dd, yyyy h:mma z", Locale.US))
java.time.format.DateTimeParseException: Text 'Wed Jul 16, 2016 4:38pm EDT' could not be parsed at index 21

I don't know what his exact problem is. When I try 'hh:mmaa' as a pattern it says that it doesn't like two a and now i am stuck, since the error messages are not helpful.

Scarberry answered 7/7, 2016 at 16:9 Comment(0)
C
32

a expects either PM or AM in upper case. To get a case insensitive formatter you need to build it manually:

DateTimeFormatter fmt = new DateTimeFormatterBuilder()
        .parseCaseInsensitive()
        .appendPattern("EEE MMM dd, yyyy h:mma z")
        .toFormatter(Locale.US);

Note that you will get a new error because the 16th of July is not a Wednesday.

Cottonseed answered 7/7, 2016 at 16:45 Comment(2)
wow.. Any idea why the default doesn't support lower case? I was converting old java.util.Date code to java.time and the SimpleDateFormat had no problems with it.Regimentals
The case depends upon your locale setting. See my answer below.Anglicism
A
7

Note that the case of AM and PM depends on your locale!

So if your locale is US it's expected to be upper case, but if it's UK it's expected to be lower case.

See: Localize the period (AM/PM) in a time stamp to another language for more details.

Anglicism answered 7/1, 2021 at 11:23 Comment(0)
T
0

It turns out this solution also resolves trying to parse mixed-case months (e.g., "Jul") using "MMM".

Thomasthomasa answered 17/5, 2018 at 19:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.