0

Help me please convert string "2022-11-28T20:02:28.215Z" to Date with time zone jn java project. This variant throws exception

String DATE_FORMAT_WITH_TIME_ZONE = "yyyy-MM-dd'T'HH:mm:sssZ";
public static Date parseString(String date) throws ParseException {
    return new SimpleDateFormat(DATE_FORMAT_WITH_TIME_ZONE).parse(date);
}
  • 4
    Double check the seconds, milliseconds in the format string. You probably want `ss.SSSZ` at the end. Also: seriously think about ditching `Date`/`Calendar`/`SimpleDateFormat` and use the newer, saner APIs from `java.time`. And in the future: when something throws an exception **show us the exception**, don't keep it to yourself. It's useful information. – Joachim Sauer Sep 01 '23 at 13:30
  • 5
    Don't use `java.util.Date`. It's superseded by `java.time` classes. `java.time.ZonedDateTime.parse("2022-11-28T20:02:28.215Z");` works perfectly well – g00se Sep 01 '23 at 13:33
  • If I understand you correctly you are asking the impossible. A `Date` cannot have a time zone. – Ole V.V. Sep 01 '23 at 16:23
  • 2
    If you need an old-fashioned `Date` object for a legacy API that you cannot upgrade to java.time just yet, still stay away from `SimpleDateFormat` since it is a notorious troublemaker of a class. Use the simple `Date.from(Instant.parse("2022-11-28T20:02:28.215Z"))`. On my computer the resulting `Date` prints as `Mon Nov 28 21:02:28 CET 2022`. It hasn’t got a time zone but prints in my default time zone (this confuses many). Since I am 1 hour ahead of UTC in November, the parsed object is correct. – Ole V.V. Sep 01 '23 at 16:31
  • 1
    `Instant.parse( "2022-11-28T20:02:28.215Z" ).atZone( ZoneId.of( "Asia/Tokyo" ) )` to get a `ZonedDateTime` object. To generate text, call `.format( DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH ) )` as seen [on Ideone.com](https://ideone.com/YBWBJ9). – Basil Bourque Sep 01 '23 at 21:55

0 Answers0