An Instant
is independent from time zones or offsets, but a LocalDateTime
is not. Although it does not have a ZoneId
or ZoneOffset
, it's values are partially based on the offset the specific zone currently has.
Here's a code example with different zones that lead to different values of the very same Instant
:
public static void main(String[] args) throws DateTimeParseException {
// example instant (see output)
var instant = Instant.now();
// get the instant with different time zones
var ldtBerlin = LocalDateTime.ofInstant(instant, ZoneId.of("Europe/Berlin"));
var ldtCanberra = LocalDateTime.ofInstant(instant, ZoneId.of("Australia/Canberra"));
var ldtKolkata = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Kolkata"));
var ldtLA = LocalDateTime.ofInstant(instant, ZoneId.of("America/Los_Angeles"));
// print all the results
System.out.println("Instant " + instant.toEpochMilli() + " in different zones:");
System.out.println(ldtBerlin + " (Berlin)");
System.out.println(ldtCanberra + " (Canberra)");
System.out.println(ldtKolkata + " (Kolkata)");
System.out.println(ldtLA + " (Los Angeles)");
}
Output:
Instant 1674724841016 in different zones:
2023-01-26T10:20:41.016228 (Berlin)
2023-01-26T20:20:41.016228 (Canberra)
2023-01-26T14:50:41.016228 (Kolkata)
2023-01-26T01:20:41.016228 (Los Angeles)
View the different values, those are the local dates and times of the zones, but a LocalDateTime
does not have any! You can use other objects, like ZonedDateTime
(has zone and offset) and OffsetDateTime
(has offset). Both of them have a method toLocalDateTime()
, in case you need a LocalDateTime
later on…