Instant and ZonedDateTime
- Java course
- Advanced
- Lesson 23/82
- 5 min
Learn time zones with Instant and ZonedDateTime.
Instant and ZonedDateTime
Instant represents a single point on the timeline in UTC. ZonedDateTime adds zone information; this lets the same moment be shown in different regions' local times.
Example: Instant now = Instant.now(). This gives the current moment in UTC. With ZonedDateTime zdt = now.atZone(ZoneId.of("Europe/Istanbul")) the moment is converted to Istanbul time. Instant is suited for storing timestamps; ZonedDateTime is for regional display.
Converting Instant and ZonedDateTime
To turn an Instant into a regional time you use atZone. The reverse is toInstant. These conversions handle time math in global systems.
Example: zdt.toInstant() turns any regional time back to UTC. This lets you compare two regions' times: first convert both to Instant, then take the difference. Since the zone information is gone, the result is always precise and comparable.
Practice Print the year with ZonedDateTime
Create a zoned datetime with ZonedDateTime.of(2024, 1, 15, 10, 30, 0, 0, ZoneId.of("UTC")). Print the year with getYear() via System.out.println.
Starter code
import java.time.ZonedDateTime;
import java.time.ZoneId;
// Create Jan 15 2024 10:30 UTC with ZonedDateTime.of
// Get the year with getYear
// Print the yearSample solution
import java.time.ZonedDateTime;
import java.time.ZoneId;
public class ZoneExample {
public static void main(String[] args) {
ZonedDateTime zdt = ZonedDateTime.of(2024, 1, 15, 10, 30, 0, 0, ZoneId.of("UTC"));
System.out.println(zdt.getYear());
}
}Expected output
2024
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the time classes
| Term | Meaning |
|---|---|
Instant |
UTC time point |
ZonedDateTime |
Time with zone |
Instant.now |
Current UTC |
ZoneId |
Zone identifier |
2 Which class represents a single UTC point in time?
- LocalDate
- Period
- Instant Correct answer
- LocalTime
Explanation: Instant is a UTC point in time.
3 Complete the atZone call
ZonedDateTime zdt = instant.____(ZoneId.of("UTC"));
ZonedDateTime zdt = instant.atZone(ZoneId.of("UTC"));
Explanation: atZone turns an Instant into a regional time.