Search code examples
javautc

How to minimize the code here which converts date string into UTC


Converting this string "2021-04-14T20:51:21.527Z" into a UTC value.

The following works, but is very verbose...

protected final LocalDateTime dateTimeOfLoss = LocalDateTime.ofInstant(Instant.parse("2021-04-14T20:51:21.527Z"), ZoneId.of(ZoneOffset.UTC.getId()));
protected final ZonedDateTime zdt = dateTimeOfLoss.atZone(ZoneId.of(ZoneOffset.UTC.getId()));

I am going for readability, this is for a test.


Solution

  • Assuming you need both of these fields, flip them round to construct the ZonedDateTime first. You can then get the LocalDateTime without having to specify the zone again:

    protected final ZonedDateTime zdt = Instant.parse("2021-04-14T20:51:21.527Z").atZone(ZoneOffset.UTC);
    protected final LocalDateTime dateTimeOfLoss = zdt.toLocalDateTime();