Java Date and Time Basics
Introduction to Java Date and Time API
Java provides robust date and time handling capabilities through its modern API, introduced in Java 8. The new Date and Time API offers significant improvements over the legacy java.util.Date
class, providing more comprehensive and intuitive date-time manipulation.
Key Date and Time Classes
LocalDate Class
LocalDate
represents a date without a time or time-zone in the ISO-8601 calendar system. It stores year, month, and day values.
LocalDate today = LocalDate.now(); // Current date
LocalDate specificDate = LocalDate.of(2023, 6, 15); // Specific date
Timestamp Class
Timestamp
represents a point in time, with millisecond precision. It extends the java.util.Date
class and includes nanosecond precision.
Date and Time API Hierarchy
graph TD
A[Java Date and Time API] --> B[LocalDate]
A --> C[LocalTime]
A --> D[LocalDateTime]
A --> E[Instant]
A --> F[ZonedDateTime]
Key Differences from Legacy Date Handling
Old Approach |
New Approach |
java.util.Date |
java.time.LocalDate |
Mutable objects |
Immutable objects |
Not thread-safe |
Thread-safe |
Limited functionality |
Rich set of methods |
Common Date and Time Operations
Creating Dates
LocalDate currentDate = LocalDate.now();
LocalDate customDate = LocalDate.of(2023, Month.JUNE, 15);
Date Manipulation
LocalDate futureDate = currentDate.plusDays(30);
LocalDate pastDate = currentDate.minusMonths(2);
Why Use Modern Date and Time API?
- More intuitive and readable
- Better performance
- Improved thread safety
- Support for different calendar systems
- Enhanced date and time calculations
Best Practices
- Use
LocalDate
for date-only scenarios
- Prefer immutable date-time classes
- Use appropriate time zone handling
- Leverage built-in methods for date manipulation
At LabEx, we recommend mastering these modern Java date and time techniques to write more robust and efficient code.