I'm receiving a UTC timestamp string from an external API, and I need to store it as a LocalDateTime
. In other words, if the timestamp is within a period when daylight saving is active, it should be adjusted to DST (usually by an hour).
I parse the incoming string to an OffsetDateTime
, which I then convert to a ZonedDateTime
, and then to an Instant
. At this point, the DST time is correctly adjusted. But when I create a LocalDateTime
from the Instant
, it loses the adjustment.
@Test
public void testDates() {
final DateTimeFormatter OFFSET_FORMAT = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXX");
final ZoneId zoneId = TimeZone.getDefault().toZoneId();
final String summerTime = "2019-09-11T10:00:00.000+0000";
final String winterTime = "2019-12-11T10:00:00.000+0000";
OffsetDateTime odtSummer = OffsetDateTime.parse(summerTime, OFFSET_FORMAT);
OffsetDateTime odtWinter = OffsetDateTime.parse(winterTime, OFFSET_FORMAT);
ZonedDateTime zdtSummer = odtSummer.toLocalDateTime().atZone(zoneId);
ZonedDateTime zdtWinter = odtWinter.toLocalDateTime().atZone(zoneId);
Instant instSummer = zdtSummer.toInstant();
Instant instWinter = zdtWinter.toInstant();
System.out.println("instSummer = " + instSummer); // instSummer = 2019-09-11T09:00:00Z
System.out.println("instWinter = " + instWinter); // instWinter = 2019-12-11T10:00:00Z
LocalDateTime ldtSummer = LocalDateTime.ofInstant(instSummer, zoneId);
LocalDateTime ldtWinter = LocalDateTime.ofInstant(instWinter, zoneId);
System.out.println("ldtSummer = " + ldtSummer); // ldtSummer = 2019-09-11T10:00
System.out.println("ldtWinter = " + ldtWinter); // ldtWinter = 2019-12-11T10:00
}
How should I do this? I don't want to resort to something ugly like re-parsing Instant.toString()
.