Master Java 8 Date & Time API: From LocalDate to ZonedDateTime
This article introduces Java 8's new date‑time API, explains the shortcomings of the old java.util.Date classes, and provides practical examples for using Instant, LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Duration, Period and DateTimeFormatter in real projects.
Background
Traditional Java date and calendar classes (java.util.Date, java.util.Calendar, SimpleDateFormat) are hard to use, lack time‑zone support, and are not thread‑safe.
Java 8 introduces a comprehensive set of date‑time APIs that clearly define concepts such as Instant, Duration, LocalDate, LocalTime, ZoneId, and Period, borrowing ideas from Joda‑Time.
Introduction
The new API resides mainly in java.time and its sub‑packages ( java.time.chrono, java.time.format, java.time.temporal, java.time.zone).
Common classes include LocalDate, LocalTime, Instant, Duration, Period, LocalDateTime and ZonedDateTime.
LocalDate : date without time, e.g., 2019‑10‑14. Useful for birthdays, anniversaries, hire dates.
LocalTime : time without date.
LocalDateTime : date and time without zone offset.
ZonedDateTime : date‑time with zone information based on UTC.
Instant : a timestamp comparable to System.currentTimeMillis() , precise to nanoseconds.
Duration : time‑based amount (seconds, minutes, etc.).
Period : date‑based amount (years, months, days).
LocalDate – Getting a Date
// only get date
LocalDate today = LocalDate.now();
System.out.println(today);
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();
System.out.printf("Year : %d Month : %d day : %d \t %n", year, month, day);You can also obtain the day of month, day of week, month length, and leap‑year status:
LocalDate today = LocalDate.now();
int dayOfMonth = today.getDayOfMonth();
DayOfWeek dayOfWeek = today.getDayOfWeek();
int length = today.lengthOfMonth();
boolean leapYear = today.isLeapYear();Creating a specific date:
LocalDate oneDay = LocalDate.of(2019, 10, 1);
System.out.println(oneDay);
LocalDate parseDay = LocalDate.parse("2019-10-01");
System.out.println(parseDay);Equality comparison is straightforward:
LocalDate oneDay = LocalDate.of(2019, 10, 1);
LocalDate anyDay = LocalDate.of(2019, 10, 1);
System.out.println(oneDay.equals(anyDay));LocalTime – Getting a Time
LocalTime localTime = LocalTime.now();
LocalTime oneTime = LocalTime.of(10, 10, 10);Formatting output shows nanosecond precision (e.g., 11:41:58.904).
// max and min constants
LocalTime maxTime = LocalTime.MAX;
LocalTime minTime = LocalTime.MIN;LocalDateTime – Combining Date and Time
LocalDateTime now = LocalDateTime.now();
LocalDateTime oneTime = LocalDateTime.of(2019, 10, 14, 10, 12, 12);
LocalTime.now().atDate(LocalDate.now());Conversion between LocalDateTime, LocalDate and LocalTime is seamless.
Instant – Timestamps
Instant now = Instant.now();
Instant specific = Instant.ofEpochSecond(365 * 24 * 60, 100);The first argument is seconds since the epoch, the second is nanoseconds.
Duration – Time Intervals
LocalDateTime from = LocalDateTime.now();
LocalDateTime to = LocalDateTime.now().plusDays(1);
Duration duration = Duration.between(from, to);
long days = duration.toDays();
long hours = duration.toHours();
long minutes = duration.toMinutes();
long seconds = duration.getSeconds();
long millis = duration.toMillis();
long nanos = duration.toNanos();Alternatively:
Duration d1 = Duration.of(7, ChronoUnit.DAYS);
Duration d2 = Duration.of(60, ChronoUnit.SECONDS);Period – Date‑Based Intervals
Period period = Period.of(1, 10, 25);
Period period1 = Period.between(LocalDate.now(), LocalDate.now().plusYears(1));ZonedDateTime – Time Zones
Set<String> allZoneIds = ZoneId.getAvailableZoneIds();
ZoneId zoneId = ZoneId.of("Asia/Shanghai");
ZonedDateTime zonedDateTime = ZonedDateTime.of(LocalDateTime.now(), zoneId);OffsetDateTime provides an immutable date‑time with a UTC offset.
Date‑Time Formatting
LocalDateTime dateTime = LocalDateTime.now();
String str = dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
System.out.println(str);
str = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(str);You can use predefined formatters or define custom patterns with ofPattern.
Key Takeaways
java.time provides robust, thread‑safe date‑time handling.
Core classes: Instant, LocalDate, LocalTime, LocalDateTime, ZonedDateTime.
DateTimeFormatter is used for parsing and formatting.
With these APIs, working with dates and times in Java 8 becomes clear, concise, and less error‑prone.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
