2

I am trying to parse the following kind of date: Dec 12 2001 11:59:59PM.

If the AM/PM wasn't next to the seconds, I would use the following pattern: MMM dd yyyy HH:mm:ss a.

However the AM/PM is ignored with the pattern MMM dd yyyy HH:mm:ssa (and is therefore always interpreted as AM).

I am trying to use a SimpleDateFormat. I tried to specify a locale to no avail.

Is this possible using a SimpleDateFormat or do I need to use an alternative method/external processing? The SimpleDateFormat particularly interests me due to its use in the pattern attribute of the @JsonFormat annotation.

Thanks.

2
  • You cannot use SimpleDateFormat to parse this input lacking any indication of time zone or offset-from-UTC. Any result will be injecting a time zone where it does not belong. See the correct Answer that uses LocalDateTime class. Commented Jun 14, 2018 at 15:04
  • 1
    I recommend you avoid the SimpleDateFormat class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in java.time, the modern Java date and time API and its DateTimeFormatter. Also DateTimeFormatter will inform you of your error if you try parsing using the pattern in the question.
    – Anonymous
    Commented Jun 14, 2018 at 16:41

5 Answers 5

4

I would like to use java.time API from Java8+ instead of the old Date :

String date = LocalDateTime.now().format(
        DateTimeFormatter.ofPattern("MMM dd yyyy hh:mm:ssa", Locale.ENGLISH)
);

or :

DateTimeFormatter format = DateTimeFormatter.ofPattern(
        "MMM dd yyyy hh:mm:ssa", Locale.ENGLISH
);
String date = LocalDateTime.of(2001, Month.DECEMBER, 12, 11, 59, 59).format(format);

Outputs

Jun 14 2018 03:01:02PM
Dec 12 2001 11:59:59AM
2
  • You’ve got the correct format pattern string and you are using the good and modern classes, that’s good. But the question is about parsing and you only demonstrate formatting…
    – Anonymous
    Commented Jun 15, 2018 at 20:24
  • This is correct @OleV.V. JoopEggen's answer already mention the real problem, In my answer I want to demonstrate the beautiful side of using java.time API Commented Jun 15, 2018 at 20:30
3

with AM/PM you want 12 hours hh instead of 24 hours HH.

hh:mm:ss''a

As k/K/h/H influence a too, now everything might work with ssa.

If ssa is still problematic (seemingly a bug), try separating the letters by an empty literal string (single quotes).


The following works:

hh:mm:ssa
2
  • Thanks, that solved it. It does work with ssa directly, using hh. Commented Jun 14, 2018 at 14:01
  • This is the (only) correct answer. "ssa" parses correctly. "HH" being 24-our clock time overrides AM/PM indicator.
    – Bohemian
    Commented Jun 14, 2018 at 14:01
2

It may very well be possible with SimpleDateFormat, but you will probably prefer to use java.time, the modern Java date and time API:

    DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("MMM dd uuuu hh:mm:ssa", Locale.ENGLISH);
    String dateTimeString = "Dec 12 2001 11:59:59PM";
    LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
    System.out.println(dateTime);

Output:

2001-12-12T23:59:59

As others have said, your problem was not with the lack of a space between seconds and AM/PM marker, but with using uppercase HH for the hours. Uppercase HH is for hour of day from 00 through 23, where what you wanted was lowercase hh for hour within AM or PM from 01 through 12.

And as yet others have said, there are issues with using SimpleDateFormat and its friend Date:

  • Those classes are long outdated.
  • Those classes are poorly designed, and SimpleDateFormat in particular is renowned for being troublesome. Your experience is typical and certainly not unusual.
  • Getting a correct result from SimpleDateFormat requires that either the JVM time zone setting agrees with the time zone understood in the string, or you set the time zone of the SimpleDateFormat to the relevant time zone. The former is hard to guarantee since the time zone setting can be changed any time from another part of your program or from other programs running in the same JVM.

This also means that if you do require an instance of the outdated Date class (for example for a legacy API that you don’t want to change just now), you will need to decide on a time zone for the conversion. Then convert for example like this:

    Instant inst = dateTime.atZone(ZoneId.of("America/Metlakatla")).toInstant();
    Date oldfashionedDate = Date.from(inst);
    System.out.println(oldfashionedDate);

I hesitate to show you the output because Date shows a quite surprising behaviour here.

Thu Dec 13 08:59:59 CET 2001

08:59? On December 13? The conversion has given you the correct point in time. When I print the Date, its toString method is invoked. This in turn uses my JVM’s time zone setting for producing the string, so the output is in a completely different time zone from the one where the conversion happened. So apparently when it’s 23:59 in Metlakatla, it’s already 08:59 the next day in Copenhagen (my time zone; CET in the output is for Central European Time). Had my JVM’s time zone setting been America/Metlakatla too, the output would have agreed more with the expected:

Wed Dec 12 23:59:59 AKST 2001

java.time is more helpful

What you asked SimpleDateFormat to do was to parse a time that had hour of day 11 and PM. This is really self contradictory since PM only begins at hour of day 12. So it would be reasonable to expect an exception from the request. A SimpleDateFormat with standard settings doesn’t give you that. It’s very typical for SimpleDateFOrmat to give you a wrong result and pretend all is well. However let’s for a moment try my modern code with your format pattern string of MMM dd yyyy HH:mm:ssa. Then we get:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'Dec 12 2001 11:59:59PM' could not be parsed: Conflict found: Field AmPmOfDay 0 differs from AmPmOfDay 1 derived from 11:59:59

I don’t claim I understand exactly why it is worded like this, but it is mentioning a conflict in the AM/PM, which is exactly what we have.

PS

I hadn’t thought at first that I’d contribute an answer, but in the end I was provoked by on one hand bohemian’s comment that only Joop Eggen’s answer was correct and on the other hand a couple of comments by Basil Bourque claiming that you could not use the SimpleDateFormat that Joop Eggen was using. So I wanted to set things straight.

Link

Oracle tutorial: Date Time explaining how to use java.time.

1

Java internally uses the builder pattern. This is slightly modified from the source code of DateTimeFormatter.RFC_1123_DATE_TIME:

I don't recommend using this over the alternative, DateTimeFormatter.ofPattern(), but it can prove more powerful in certain scenarios where you hit the limitations of ofPattern.

    Map<Long, String> moy = new HashMap<>();
    moy.put(1L, "Jan"); moy.put(2L, "Feb"); moy.put(3L, "Mar");
    moy.put(4L, "Apr"); moy.put(5L, "May"); moy.put(6L, "Jun");
    moy.put(7L, "Jul"); moy.put(8L, "Aug"); moy.put(9L, "Sep");
    moy.put(10L, "Oct"); moy.put(11L, "Nov"); moy.put(12L, "Dec");
    DateTimeFormatter format = new DateTimeFormatterBuilder()
            .appendText(MONTH_OF_YEAR, moy)
            .appendLiteral(' ')
            .appendValue(DAY_OF_MONTH, 2)
            .appendLiteral(' ')
            .appendValue(YEAR, 4, 4, EXCEEDS_PAD)
            .appendLiteral(' ')
            .appendValue(HOUR_OF_AMPM, 1, 2, NOT_NEGATIVE)
            .appendLiteral(':')
            .appendValue(MINUTE_OF_HOUR, 1, 2, NOT_NEGATIVE)
            .optionalStart()
            .appendLiteral(':')
            .appendValue(SECOND_OF_MINUTE, 1, 2, NOT_NEGATIVE)
            .optionalEnd()
            .appendText(AMPM_OF_DAY)
            .toFormatter();

    System.out.println(format.parse("Jun 14 2018 2:51:22AM")); // {},ISO resolved to 2018-06-14T02:51:22
    System.out.println(format.parse("Jun 14 2018 2:51:22PM")); // {},ISO resolved to 2018-06-14T14:51:22
1
  • Isn’t that quite a bit more complicated than needed? Using java.time is a good idea.
    – Anonymous
    Commented Jun 14, 2018 at 16:43
0

Note

Unfortunately, the below code is inaccurate. AM/PM marker is never read. Depending on the local time, either AM or PM is assumed.

Original answer

Use the following format string "MMM dd yyyy HH:mm:ssaaa".

String str = "Jun 14 2018 13:53:19PM";
DateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ssaaa");
try {
  Date date = df.parse(str);
  System.out.print(df.format(date));
} catch (ParseException e) {
  e.printStackTrace();
}
13
  • Can you please provide more information on your downvote? Knowing that the code is working AND answers the question? Commented Jun 14, 2018 at 14:18
  • 1
    Perhaps their down-vote was because you are using terribly troublesome old date-time classes that were supplanted years ago by the excellent industry-leading java.time classes built into Java 8 and later. Also available in Java 6 & 7 via the ThreeTen-Backport project. So there is no reason to be using those legacy classes. Suggesting their use in 2018 is poor advice indeed. Why drive a Yugo when there is a Honda Civic in your driveway? Commented Jun 14, 2018 at 14:43
  • 1
    I believe that I accurately answered the question (I quote "The SimpleDateFormat particularly interests me") without involving my personal opinion. Commented Jun 14, 2018 at 14:49
  • 1
    Hi, I didn't down vote but I'm afraid this solution doesn't work - at least not on my machine - most likely due to the same reason mine didn't : capital HH suppressing the AM/PM reading. It should be hh. Also down voting because you're actually answering the question instead of telling me not to use deprecated stuff would be the dumbest thing. "We can do better now" should imo only be a sidenote to an actual answer. Using deprecated stuff is my problem - you don't know if for some reason I can't do otherwise. Commented Jun 15, 2018 at 10:03
  • 1
    For keeping the answer: If you want to keep the reputation points from 1 upvote and 1 downvote, that’s fair. Maybe you can improve the answer? I don’t know if you want to. As I said, some readers may learn from the discussion under the answer. For deleting: The answer does have the mentioned issues. I’ll leave it up to you. I have myself hesitated to delete downvoted answers, but have often included comments in the answer (using the edit link) so the reader knows if there are issues. I think it’s a matter of style, not of obligation.
    – Anonymous
    Commented Jun 15, 2018 at 12:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.