Java Date and Time
Before Java 8, handling dates and times mainly relied on java.util.Date and java.util.Calendar classes, which had design flaws, were not thread-safe, and had a confusing API. Starting from Java 8, a completely new java.time package was introduced, providing immutable, thread-safe, and clearly designed APIs, which is the standard way to handle dates and times in modern Java development.
Core Classes in the java.time Package
LocalDate: Represents a date without a time zone (year-month-day). Example:2024-07-25.LocalTime: Represents a time without a time zone (hour:minute:second.nanosecond). Example:15:30:00.LocalDateTime: Represents a combination of date and time without a time zone. Example:2024-07-25T15:30:00.ZonedDateTime: Represents a date and time with a time zone. This is the preferred choice when dealing with scenarios that require time zone conversions.Instant: Represents an instantaneous point on the timeline (timestamp), typically used for time recording between machines, internally based on UTC time zone.DateTimeFormatter: Used to format and parse date-time objects.
Creating Date and Time Objects
Getting the current date and time is very simple.
You can also use the of() method to create specific dates and times.
Manipulating Date and Time
All objects in the java.time API are immutable, and any modification operation returns a new instance.
Getting Date-Time Information
You can easily extract the parts you need from date-time objects.
Formatting and Parsing
DateTimeFormatter is the core tool for formatting and parsing date-time.
Java also provides some predefined formatters, such as DateTimeFormatter.ISO_LOCAL_DATE_TIME.
Calculating Time Differences
Period: Used to calculate the difference between two dates (LocalDate), in units of years, months, and days.Duration: Used to calculate the difference between two time points (LocalTime,LocalDateTime,Instant), in units of days, hours, minutes, seconds, and nanoseconds.