1
try {
    SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD'T'HH:mm:ss+hh:mm");
    Date dateTime = format .parse("2020-11-22T05:57:10+01:00");
    System.out.println(dateTime);
} catch (ParseException e) {
    e.printStackTrace();
}

Above out put is Sun Dec 29 05:00:10 IST 2019 the 57 minutes part is lost. The above date I am receiving from JSON response with TimeZone Europe/Berlin. Currently I haven't include TimeZone. What is correct way to address this string while converting into Java Date object?

Does the above conversion is correct ? If not then how to convert this data ?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • Your format is incorrect. It should probably be `yyyy-MM-dd'T'HH:mm:ssZ` note that the format is *case sensitive* `DD` is not the same as `dd` – Lino Jan 29 '21 at 09:22
  • 3
    Additionally you should move away from the `java.util.Date`-class and to the ones provided in the `java.time`-package introduced in Java 8. These new classes are much easier to use and have a lot of benefits compared to their old counterparts – Lino Jan 29 '21 at 09:25
  • @Lino Your probably answer does not helped me, it is failing in runtime with unparseable string. and link also mentioned does not having similar format. can you please reopen this question. – Dnyaneshwar Jadhav Jan 29 '21 at 09:31
  • 1
    I made a typo in the original format. The `Z` at the end should be an `X`: `yyyy-MM-dd'T'HH:mm:ssX` – Lino Jan 29 '21 at 09:35
  • 1
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead just use `OffsetDateTime` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jan 30 '21 at 18:00
  • 1
    I added a couple more of links to original questions. Please see if they aren’t helpful. And do search for yet more. If you still are not getting through. please post a new qusetion including what you’ve learned and what you think you are still missing. We are here to help. – Ole V.V. Jan 30 '21 at 18:04
  • Thanks @OleV.V. I read some API's of Joda-Time. And it is directly consider the string format date-time and automatically convert into Date & Time with TimeZone. Does joda-time always convert into UTC time format ? because after putting code into Joda lib it is giving me UTC time. Your additional links are more useful :) – Dnyaneshwar Jadhav Feb 01 '21 at 14:00
  • *Does joda-time always convert into UTC time*? No, it depends entirely on the code. It will standard parse into the default time zone of the JVM, so if that is UTC, it probably explains your observation. The `withOffsetParsed` method of `DateTimeFormattter` instructs Joda-Time to use the offset from the string instead. But if possible, you should probably prefer java.time over Joda-Time. – Ole V.V. Feb 01 '21 at 20:02

0 Answers0