Introduction
The Java Date and Time API, introduced in Java 8, provides a comprehensive model for date and time handling. The new API is based on the ISO-8601 calendar system and is intended to replace the old java.util.Date
and java.util.Calendar
classes. The API is designed to be easy to use and understand, providing a more natural and expressive way to work with dates and times.
Key Points:
- Immutability: All classes in the new Date and Time API are immutable and thread-safe.
- Separation of Concerns: Separate classes for different use cases, such as
LocalDate
for dates,LocalTime
for times, andLocalDateTime
for both. - Time Zones: Improved support for time zones with
ZonedDateTime
andOffsetDateTime
. - Fluent API: Methods that return instances of the same type to allow for method chaining.
Table of Contents
- Important Classes and Methods
- LocalDate
- LocalTime
- LocalDateTime
- ZonedDateTime
- OffsetDateTime
- Period
- Duration
- Instant
- DateTimeFormatter
- Working with LocalDate
- Working with LocalTime
- Working with LocalDateTime
- Working with ZonedDateTime and OffsetDateTime
- Working with Period and Duration
- Working with Instant
- Formatting and Parsing Dates and Times
- Conclusion
2. Working with LocalDate
Represents a date without a time-zone in the ISO-8601 calendar system.
Important Methods:
- now(): Returns the current date.
- of(int year, int month, int dayOfMonth): Obtains an instance of
LocalDate
from a year, month, and day. - parse(CharSequence text): Obtains an instance of
LocalDate
from a text string. - plusDays(long daysToAdd): Returns a copy of this date with the specified number of days added.
- minusDays(long daysToSubtract): Returns a copy of this date with the specified number of days subtracted.
- getDayOfWeek(): Returns the day-of-week of this date.
Example:
import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class LocalDateExample { public static void main(String[] args) { // Current date LocalDate currentDate = LocalDate.now(); System.out.println("Current date: " + currentDate); // Specific date LocalDate specificDate = LocalDate.of(2023, 6, 13); System.out.println("Specific date: " + specificDate); // Parsing date LocalDate parsedDate = LocalDate.parse("2023-06-13"); System.out.println("Parsed date: " + parsedDate); // Formatting date DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); String formattedDate = currentDate.format(formatter); System.out.println("Formatted date: " + formattedDate); // Adding days LocalDate addedDate = currentDate.plusDays(5); System.out.println("Date after adding 5 days: " + addedDate); // Subtracting days LocalDate subtractedDate = currentDate.minusDays(5); System.out.println("Date after subtracting 5 days: " + subtractedDate); // Getting the day of the week System.out.println("Day of the week: " + currentDate.getDayOfWeek()); } }
Explanation:
- now(): Gets the current date.
- of(): Creates a
LocalDate
from year, month, and day. - parse(): Parses a date string to create a
LocalDate
. - format(): Formats the date using a specific pattern.
- plusDays(): Adds days to the date.
- minusDays(): Subtracts days from the date.
- getDayOfWeek(): Gets the day of the week.
3. Working with LocalTime
Represents a time without a date in the ISO-8601 calendar system.
Important Methods:
- now(): Returns the current time.
- of(int hour, int minute, int second): Obtains an instance of
LocalTime
from an hour, minute, and second. - parse(CharSequence text): Obtains an instance of
LocalTime
from a text string. - plusHours(long hoursToAdd): Returns a copy of this time with the specified number of hours added.
- minusMinutes(long minutesToSubtract): Returns a copy of this time with the specified number of minutes subtracted.
- withHour(int hour): Returns a copy of this time with the hour-of-day altered.
Example:
import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class LocalTimeExample { public static void main(String[] args) { // Current time LocalTime currentTime = LocalTime.now(); System.out.println("Current time: " + currentTime); // Specific time LocalTime specificTime = LocalTime.of(10, 15, 30); System.out.println("Specific time: " + specificTime); // Parsing time LocalTime parsedTime = LocalTime.parse("10:15:30"); System.out.println("Parsed time: " + parsedTime); // Formatting time DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a"); String formattedTime = currentTime.format(formatter); System.out.println("Formatted time: " + formattedTime); // Adding hours LocalTime addedTime = currentTime.plusHours(2); System.out.println("Time after adding 2 hours: " + addedTime); // Subtracting minutes LocalTime subtractedTime = currentTime.minusMinutes(30); System.out.println("Time after subtracting 30 minutes: " + subtractedTime); // Changing the hour LocalTime changedHourTime = currentTime.withHour(5); System.out.println("Time with changed hour: " + changedHourTime); } }
Explanation:
- now(): Gets the current time.
- of(): Creates a
LocalTime
from hour, minute, and second. - parse(): Parses a time string to create a
LocalTime
. - format(): Formats the time using a specific pattern.
- plusHours(): Adds hours to the time.
- minusMinutes(): Subtracts minutes from the time.
- withHour(): Changes the hour of the time.
4. Working with LocalDateTime
Represents a date-time without a time-zone in the ISO-8601 calendar system.
Important Methods:
- now(): Returns the current date-time.
- of(int year, int month, int dayOfMonth, int hour, int minute, int second): Obtains an instance of
LocalDateTime
from a date and time. - parse(CharSequence text): Obtains an instance of
LocalDateTime
from a text string. - plusDays(long daysToAdd): Returns a copy of this date-time with the specified number of days added.
- minusHours(long hoursToSubtract): Returns a copy of this date-time with the specified number of hours subtracted.
- toLocalDate(): Extracts the
LocalDate
part of this date-time.
Example:
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class LocalDateTimeExample { public static void main(String[] args) { // Current date-time LocalDateTime currentDateTime = LocalDateTime.now(); System.out.println("Current date-time: " + currentDateTime); // Specific date-time LocalDateTime specificDateTime = LocalDateTime.of(2023, 6, 13, 10, 15, 30); System.out.println("Specific date-time: " + specificDateTime); // Parsing date-time LocalDateTime parsedDateTime = LocalDateTime.parse("2023-06-13T10:15:30"); System.out.println("Parsed date-time: " + parsedDateTime); // Formatting date-time DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); String formattedDateTime = currentDateTime.format(formatter); System.out.println("Formatted date-time: " + formattedDateTime); // Adding days LocalDateTime addedDateTime = currentDateTime.plusDays(5); System.out.println("Date-time after adding 5 days: " + addedDateTime); // Subtracting hours LocalDateTime subtractedDateTime = currentDateTime.minusHours(3); System.out.println("Date-time after subtracting 3 hours: " + subtractedDateTime); // Extracting the date part System.out.println("Date part: " + currentDateTime.toLocalDate()); // Extracting the time part System.out.println("Time part: " + currentDateTime.toLocalTime()); } }
Explanation:
- now(): Gets the current date-time.
- of(): Creates a
LocalDateTime
from year, month, day, hour, minute, and second. - parse(): Parses a date-time string to create a
LocalDateTime
. - format(): Formats the date-time using a specific pattern.
- plusDays(): Adds days to the date-time.
- minusHours(): Subtracts hours from the date-time.
- toLocalDate(): Extracts the date part from the date-time.
- toLocalTime(): Extracts the time part from the date-time.
5. Working with ZonedDateTime and OffsetDateTime
ZonedDateTime
Represents a date-time with a time-zone in the ISO-8601 calendar system.
Important Methods:
- now(): Returns the current date-time with the system default time-zone.
- of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond, ZoneId zone): Obtains an instance of
ZonedDateTime
from a date-time and zone. - parse(CharSequence text): Obtains an instance of
ZonedDateTime
from a text string. - plusMonths(long monthsToAdd): Returns a copy of this date-time with the specified number of months added.
- minusMinutes(long minutesToSubtract): Returns a copy of this date-time with the specified number of minutes subtracted.
- toLocalDateTime(): Extracts the
LocalDateTime
part of this date-time.
OffsetDateTime
Represents a date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system.
Important Methods:
- now(): Returns the current date-time with the system default offset.
- of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond, ZoneOffset offset): Obtains an instance of
OffsetDateTime
from a date-time and offset. - parse(CharSequence text): Obtains an instance of
OffsetDateTime
from a text string. - plusWeeks(long weeksToAdd): Returns a copy of this date-time with the specified number of weeks added.
- minusSeconds(long secondsToSubtract): Returns a copy of this date-time with the specified number of seconds subtracted.
- toLocalDateTime(): Extracts the
LocalDateTime
part of this date-time.
ZonedDateTime and OffsetDateTime Examples:
import java.time.ZonedDateTime; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; public class ZonedDateTimeExample { public static void main(String[] args) { // Current ZonedDateTime ZonedDateTime currentZonedDateTime = ZonedDateTime.now(); System.out.println("Current ZonedDateTime: " + currentZonedDateTime); // Specific ZonedDateTime ZonedDateTime specificZonedDateTime = ZonedDateTime.of(2023, 6, 13, 10, 15, 30, 0, ZoneId.of("Europe/Paris")); System.out.println("Specific ZonedDateTime: " + specificZonedDateTime); // Parsing ZonedDateTime ZonedDateTime parsedZonedDateTime = ZonedDateTime.parse("2023-06-13T10:15:30+02:00[Europe/Paris]"); System.out.println("Parsed ZonedDateTime: " + parsedZonedDateTime); // Formatting ZonedDateTime DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy - HH:mm:ss Z"); String formattedZonedDateTime = currentZonedDateTime.format(formatter); System.out.println("Formatted ZonedDateTime: " + formattedZonedDateTime); // Adding months ZonedDateTime addedZonedDateTime = currentZonedDateTime.plusMonths(3); System.out.println("ZonedDateTime after adding 3 months: " + addedZonedDateTime); // Subtracting minutes ZonedDateTime subtractedZonedDateTime = currentZonedDateTime.minusMinutes(30); System.out.println("ZonedDateTime after subtracting 30 minutes: " + subtractedZonedDateTime); // Extracting LocalDateTime from ZonedDateTime System.out.println("LocalDateTime part: " + currentZonedDateTime.toLocalDateTime()); // Current OffsetDateTime OffsetDateTime currentOffsetDateTime = OffsetDateTime.now(); System.out.println("Current OffsetDateTime: " + currentOffsetDateTime); // Specific OffsetDateTime OffsetDateTime specificOffsetDateTime = OffsetDateTime.of(2023, 6, 13, 10, 15, 30, 0, ZoneOffset.of("+02:00")); System.out.println("Specific OffsetDateTime: " + specificOffsetDateTime); // Parsing OffsetDateTime OffsetDateTime parsedOffsetDateTime = OffsetDateTime.parse("2023-06-13T10:15:30+02:00"); System.out.println("Parsed OffsetDateTime: " + parsedOffsetDateTime); // Formatting OffsetDateTime String formattedOffsetDateTime = currentOffsetDateTime.format(formatter); System.out.println("Formatted OffsetDateTime: " + formattedOffsetDateTime); // Adding weeks OffsetDateTime addedOffsetDateTime = currentOffsetDateTime.plusWeeks(2); System.out.println("OffsetDateTime after adding 2 weeks: " + addedOffsetDateTime); // Subtracting seconds OffsetDateTime subtractedOffsetDateTime = currentOffsetDateTime.minusSeconds(60); System.out.println("OffsetDateTime after subtracting 60 seconds: " + subtractedOffsetDateTime); // Extracting LocalDateTime from OffsetDateTime System.out.println("LocalDateTime part: " + currentOffsetDateTime.toLocalDateTime()); } }
Explanation:
- now(): Gets the current
ZonedDateTime
orOffsetDateTime
. - of(): Creates a
ZonedDateTime
orOffsetDateTime
from date, time, and zone/offset. - parse(): Parses a date-time string to create a
ZonedDateTime
orOffsetDateTime
. - format(): Formats the date-time using a specific pattern.
- plusMonths(): Adds months to the date-time.
- minusMinutes(): Subtracts minutes from the date-time.
- toLocalDateTime(): Extracts the
LocalDateTime
part from the date-time.
6. Working with Period and Duration
Period
Represents a date-based amount of time in the ISO-8601 calendar system.
Important Methods:
- ofYears(int years): Obtains a
Period
representing a number of years. - ofMonths(int months): Obtains a
Period
representing a number of months. - ofDays(int days): Obtains a
Period
representing a number of days. - between(LocalDate startDateInclusive, LocalDate endDateExclusive): Obtains a
Period
representing the period between two dates. - plusMonths(long monthsToAdd): Returns a copy of this period with the specified number of months added.
- minusDays(long daysToSubtract): Returns a copy of this period with the specified number of days subtracted.
Duration
Represents a time-based amount of time in the ISO-8601 calendar system.
Important Methods:
- ofHours(long hours): Obtains a
Duration
representing a number of hours. - ofMinutes(long minutes): Obtains a
Duration
representing a number of minutes. - ofSeconds(long seconds): Obtains a
Duration
representing a number of seconds. - between(Temporal startInclusive, Temporal endExclusive): Obtains a
Duration
representing the duration between two temporal objects. - plusMillis(long millisToAdd): Returns a copy of this duration with the specified number of milliseconds added.
- minusNanos(long nanosToSubtract): Returns a copy of this duration with the specified number of nanoseconds subtracted.
Period and Duration Examples:
import java.time.LocalDate; import java.time.LocalTime; import java.time.Period; import java.time.Duration; public class PeriodDurationExample { public static void main(String[] args) { // Period example LocalDate startDate = LocalDate.of(2023, 1, 1); LocalDate endDate = LocalDate.of(2023, 6, 13); Period period = Period.between(startDate, endDate); System.out.println("Period: " + period); // Period: P5M12D // Adding Period LocalDate datePlusPeriod = startDate.plus(period); System.out.println("Date after adding period: " + datePlusPeriod); // 2023-06-13 // Duration example LocalTime startTime = LocalTime.of(10, 15, 30); LocalTime endTime = LocalTime.of(12, 45, 50); Duration duration = Duration.between(startTime, endTime); System.out.println("Duration: " + duration); // Duration: PT2H30M20S // Adding Duration LocalTime timePlusDuration = startTime.plus(duration); System.out.println("Time after adding duration: " + timePlusDuration); // 12:45:50 } }
Explanation:
- Period.between(): Creates a
Period
between twoLocalDate
instances. - plus(Period): Adds a
Period
to aLocalDate
. - Duration.between(): Creates a
Duration
between twoLocalTime
instances. - plus(Duration): Adds a
Duration
to aLocalTime
.
7. Working with Instant
Represents a point in time.
Important Methods:
- now(): Returns the current instant.
- ofEpochSecond(long epochSecond): Obtains an instance of
Instant
using seconds from the epoch of 1970-01-01T00:00:00Z. - parse(CharSequence text): Obtains an instance of
Instant
from a text string. - plusSeconds(long secondsToAdd): Returns a copy of this instant with the specified number of seconds added.
- minusMillis(long millisToSubtract): Returns a copy of this instant with the specified number of milliseconds subtracted.
- toEpochMilli(): Converts this instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z.
Example:
import java.time.Instant; public class InstantExample { public static void main(String[] args) { // Current instant Instant currentInstant = Instant.now(); System.out.println("Current instant: " + currentInstant); // Specific instant Instant specificInstant = Instant.parse("2023-06-13T10:15:30.00Z"); System.out.println("Specific instant: " + specificInstant); // Adding seconds to instant Instant addedInstant = currentInstant.plusSeconds(3600); System.out.println("Instant plus one hour: " + addedInstant); // Subtracting milliseconds from instant Instant subtractedInstant = currentInstant.minusMillis(5000); System.out.println("Instant minus 5000 milliseconds: " + subtractedInstant); // Getting epoch milliseconds long epochMilli = currentInstant.toEpochMilli(); System.out.println("Epoch milliseconds: " + epochMilli); } }
Explanation:
- now(): Gets the current
Instant
. - ofEpochSecond(): Creates an
Instant
using seconds from the epoch. - parse(): Parses an instant string to create an
Instant
. - plusSeconds(): Adds seconds to the instant.
- minusMillis(): Subtracts milliseconds from the instant.
- toEpochMilli(): Converts the instant to milliseconds from the epoch.
8. Formatting and Parsing Dates and Times
Example:
import java.time.LocalDate; import java.time.LocalTime; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateTimeFormatterExample { public static void main(String[] args) { // Formatting LocalDate LocalDate date = LocalDate.now(); DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); String formattedDate = date.format(dateFormatter); System.out.println("Formatted LocalDate: " + formattedDate); // Parsing LocalDate String dateString = "13/06/2023"; LocalDate parsedDate = LocalDate.parse(dateString, dateFormatter); System.out.println("Parsed LocalDate: " + parsedDate); // Formatting LocalTime LocalTime time = LocalTime.now(); DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm:ss a"); String formattedTime = time.format(timeFormatter); System.out.println("Formatted LocalTime: " + formattedTime); // Parsing LocalTime String timeString = "10:15:30 AM"; LocalTime parsedTime = LocalTime.parse(timeString, timeFormatter); System.out.println("Parsed LocalTime: " + parsedTime); // Formatting LocalDateTime LocalDateTime dateTime = LocalDateTime.now(); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); String formattedDateTime = dateTime.format(dateTimeFormatter); System.out.println("Formatted LocalDateTime: " + formattedDateTime); // Parsing LocalDateTime String dateTimeString = "13/06/2023 10:15:30"; LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeString, dateTimeFormatter); System.out.println("Parsed LocalDateTime: " + parsedDateTime); } }
Explanation:
- ofPattern(): Creates a
DateTimeFormatter
with a specific pattern. - format(): Formats a date-time object using the formatter.
- parse(): Parses a date-time string to create a date-time object.
9. Conclusion
The Java Date and Time API provides a powerful and flexible way to handle dates and times. By leveraging classes such as LocalDate
, LocalTime
, LocalDateTime
, ZonedDateTime
, OffsetDateTime
, Period
, Duration
, Instant
, and DateTimeFormatter
, you can perform a wide range of date and time operations in a clear and concise manner.