0

i tried to convert a date String into a date object, but unfortunately the month is set every time to Jan and I can't figure out why.

    String date = "20190522T072424.000Z";
    DateFormat sdf = new SimpleDateFormat("yyyyMMDD'T'HHmmss.SSS'Z'");
    System.out.println(sdf.parse(date));

Output: Tue Jan 22 07:24:24 CET 2019

  • 5
    Try with lowercase `dd`, `DD` is for Day in year so the 22th day in the year is in january. [Check the SimpleDateFormat doc](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html). This is just a typo, voting to close. – AxelH May 23 '19 at 09:56
  • Please read the [docs](https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html) – QBrute May 23 '19 at 09:57
  • 1
    I have no idea about Jan but your parser is wrong in general. Z at the end of time is UTC timezone. You parse it as constant text and get CET timezone. It is wrong. – Alexander Pavlov May 23 '19 at 09:59
  • 1
    You shouldn't use the obsolete `Date`, `Calendar` and `SimpleDateFormat`. Use the new Java Date and Time API, available in the `java.time` package, instead. – MC Emperor May 23 '19 at 10:06
  • Funnily your string is in ISO 8601 format, and while the classes of java.time generally parse ISO 8601 format without any explicit formatter, they don’t accept this variant. However, `DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmss.SSSX")` parses your string. – Ole V.V. May 23 '19 at 10:34
  • What @MCEmperor said, except java.time isn’t actually brand new, it’s been around for 5 years. There really isn’t any excuse for not using it in 2019. – Ole V.V. May 23 '19 at 15:45
  • 1
    What @OleVV said, there's absolutely no excuse not to use it. [Here's what's wrong with the old classes](https://stackoverflow.com/questions/1969442/whats-wrong-with-java-date-time-api). – MC Emperor May 23 '19 at 18:59

1 Answers1

0

As AxelH said, the format DD is for day of the year. If you use yyyyMMdd'T'HHmmss.SSS'Z' you will print Wed May 22 07:24:24 WEST 2019.

For reference: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

AxelH
  • 14,325
  • 2
  • 25
  • 55