⏰ Let’s talk about ZonedDateTime
, the most precise and complete date-time class in Java 8’s java.time
package.
✅ What is ZonedDateTime
?
ZonedDateTime
is a class that represents:
📅 Date + 🕒 Time + 🌍 Time Zone
🔹 Example:
2025-04-15T10:30:00+05:00[Asia/Yekaterinburg]
It contains:
LocalDateTime
→ date + time- Zone offset → e.g.,
+05:00
- Zone ID → e.g.,
Asia/Yekaterinburg
✅ When to Use ZonedDateTime
Use it when:
- You need to represent time with timezone awareness
- You’re dealing with global systems, scheduling, or timezone conversions
- You want accurate Daylight Saving Time (DST) handling
How to Create a ZonedDateTime
🔹 1. Current date-time in system default zone:
ZonedDateTime now = ZonedDateTime.now();
System.out.println(now); // e.g., 2025-04-15T10:30+05:00[Asia/Yekaterinburg]
🔹 2. From a specific zone:
ZonedDateTime nowInNY = ZonedDateTime.now(ZoneId.of("America/New_York"));
🔹 3. From a LocalDateTime
and ZoneId
:
LocalDateTime ldt = LocalDateTime.of(2025, 4, 15, 10, 30);
ZonedDateTime zdt = ldt.atZone(ZoneId.of("Europe/Paris"));
✅ Useful Methods
Method | Description |
---|---|
now() | Current date-time in system zone |
withZoneSameInstant() | Convert to a different time zone (keep exact moment in time) |
getZone() | Get the zone info |
toLocalDateTime() | Drop the zone and get a LocalDateTime |
format(...) | Format for display |
🧠 Example: Convert from One Zone to Another
ZonedDateTime moscowTime = ZonedDateTime.now(ZoneId.of("Europe/Moscow"));
ZonedDateTime laTime = moscowTime.withZoneSameInstant(ZoneId.of("America/Los_Angeles"));
System.out.println("Moscow: " + moscowTime);
System.out.println("LA: " + laTime);
❓ ZonedDateTime vs LocalDateTime
Feature | LocalDateTime | ZonedDateTime |
---|---|---|
Includes TimeZone | ❌ No | ✅ Yes |
DST Aware | ❌ No | ✅ Yes |
Suitable for Logs | ✅ Often | ❌ Only if zone needed |
Suitable for Global | ❌ No | ✅ Yes |