Date and time (Java)

JSR-310 and JSR-310 extras

Package java.time in Java 8 and later implement JSR-310.

Additional functionality is available from library ThreeTen [https://www.threeten.org/].

Maven dependency at [https://mvnrepository.com/artifact/org.threeten/threeten-extra].


org.threeten.extra.Interval

Javadoc > https://www.threeten.org/threeten-extra/apidocs/org.threeten.extra/org/threeten/extra/Interval.html

An interval represents the time on the time-line between two Instants. The class stores the start and end instants, with the start inclusive and the end exclusive.


LocalTime into a specific date and geographic region time-zone

Use case: Given a local time (eg: 15:30:59), let's obtain the proper ZonedDateTime for a specific date (eg: 2020-08-20) and geographic region (eg: "Europe/Madrid").


Expected result:

The local time 15:30:59 in a winter time date must be in the UTC+1 time-zone; and in a summer time date must be in the UTC+2 time-zone.


Sample code:

LocalTime lt = LocalTime.of(15, 30, 59);

System.out.println("Local time = " + lt);


LocalDateTime ldtWinter = lt.atDate(LocalDate.of(2020, 2, 10));
LocalDateTime ldtSummer = lt.atDate(LocalDate.of(2020, 8, 20));

System.out.println("\n");
System.out.println("Datetime February = " + ldtWinter);
System.out.println("Datetime August = " + ldtSummer);


ZonedDateTime zdtWinter = ldtWinter.atZone(ZoneId.of("Europe/Madrid"));
ZonedDateTime zdtSummer = ldtSummer.atZone(ZoneId.of("Europe/Madrid"));

System.out.println("\n");
System.out.println("zdtWinter = " + zdtWinter);
System.out.println("zdtSummer = " + zdtSummer);


Sample output:

Note that the same local time becomes UTC+1 on Winter but UTC+2 on a Summer daylight saving date.

Local time = 15:30:59


Datetime February = 2020-02-10T15:30:59
Datetime August = 2020-08-20T15:30:59


zdtWinter = 2020-02-10T15:30:59+01:00[Europe/Madrid]
zdtSummer = 2020-08-20T15:30:59+02:00[Europe/Madrid]