0

I have following code to parse and format a date:

          SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm a");
          System.out.println("Before Format  " + dateTimeFormatter.parse("06/19/2018 11:17 PM"));
          System.out.println(dateTimeFormatter.format(dateTimeFormatter.parse("06/19/2018 11:17 PM")));

output of this is appearing as following:

Before Format  Tue Jun 19 11:17:00 IST 2018
06/19/2018 11:17 AM

Why PM is printer as AM in it?

  • 1
    You need to use `hh` (12 hours clock) instead of `HH` (24 hours clock) –  Jun 19 '18 at 11:23
  • @Codeer That was super fast and accurate. How can I mark it as an answer? – Abhishek Gupta Jun 19 '18 at 11:24
  • I'm trying to see if I can find a duplicate of this question so therefore I posted it as a comment. I will post it as an answer as I can not find it so far. –  Jun 19 '18 at 11:26
  • @Codeer Interestingly enough, it took me about 5 seconds with my best buddy Google to find a duplicate ;-). The OP, I would recommend to simply study the documentation **first** the next time. – GhostCat Jun 19 '18 at 11:31
  • @GhostCat I tend to use the on-site search when looking for duplicates. I don't know why I never turned to google before myself. –  Jun 19 '18 at 11:33
  • 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](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 19 '18 at 11:43
  • @Codeer Final word here, an URL: https://meta.stackoverflow.com/questions/289364/why-is-duplicate-search-still-awful ... – GhostCat Jun 19 '18 at 12:07
  • 1
    @GhostCat Thanks a lot! I will definitely use this new knowledge to find duplicates the easier way. I'm always looking to improve my contribution on this site so thank you for pointing me to that meta question. As for coding in a hex editor... I'll stick to Java for now ;) –  Jun 19 '18 at 12:09
  • @Codeer Rest assured, I didn't find that URL using the SO built-in search. But enough for now ;-) – GhostCat Jun 19 '18 at 12:18

1 Answers1

3

When you want to display a time in AM/PM format, it is important to use a 12-hours clock (hh) instead of a 24-hours clock (HH).

Instead of MM/dd/yyyy HH:mm a the format needs to be MM/dd/yyyy hh:mm a

For more information about SimpleDateFormat check out the documentation here

  • 1
    Nice answer though. And ending up with 666 is cool anyway. I am almost hesitant to damage that perfect number. Almost. – GhostCat Jun 19 '18 at 11:32