Modern Java Time API
Introduction to java.time Package
Java 8 introduced a comprehensive date and time API that resolves many previous limitations. The java.time
package provides robust, immutable, and thread-safe date-time classes.
Core Time API Classes
Class |
Purpose |
Key Characteristics |
LocalDate |
Date without time |
Year, month, day |
LocalTime |
Time without date |
Hour, minute, second |
LocalDateTime |
Date and time |
Combines date and time |
ZonedDateTime |
Date and time with time zone |
Full timestamp with zone info |
Instant |
Machine timestamp |
Epoch seconds |
Basic Date Operations
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.ZoneId;
public class ModernDateAPIExample {
public static void main(String[] args) {
// Current date
LocalDate today = LocalDate.now();
System.out.println("Current Date: " + today);
// Specific date
LocalDate specificDate = LocalDate.of(2023, 12, 31);
System.out.println("Specific Date: " + specificDate);
// Date calculations
LocalDate futureDate = today.plusDays(30);
System.out.println("Date after 30 days: " + futureDate);
}
}
Date and Time Manipulation
graph TD
A[LocalDate/LocalTime] --> B[Modification Methods]
B --> C[plus/minus Operations]
B --> D[with Operations]
C --> E[Add/Subtract Time]
D --> F[Modify Specific Components]
Advanced Date Calculations
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class DateCalculationExample {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2023, 1, 1);
LocalDate end = LocalDate.of(2023, 12, 31);
// Calculate period between dates
Period period = Period.between(start, end);
System.out.println("Period: " + period.getMonths() + " months");
// Calculate days between dates
long daysBetween = ChronoUnit.DAYS.between(start, end);
System.out.println("Days between: " + daysBetween);
}
}
Time Zone Handling
public class TimeZoneExample {
public static void main(String[] args) {
// Current zoned date time
ZonedDateTime nowInNewYork = ZonedDateTime.now(ZoneId.of("America/New_York"));
System.out.println("New York Time: " + nowInNewYork);
// Convert between time zones
ZonedDateTime tokyoTime = nowInNewYork.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
System.out.println("Tokyo Time: " + tokyoTime);
}
}
import java.time.format.DateTimeFormatter;
public class DateFormattingExample {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
// Custom formatting
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String formattedDate = date.format(formatter);
System.out.println("Formatted Date: " + formattedDate);
}
}
LabEx Insights
At LabEx, we recommend fully embracing the java.time
API for all new Java projects. Its design addresses previous date handling challenges and provides a more intuitive approach to working with dates and times.