LocalDate
LocalDate is a class in the Java 8 Date and Time API (java.time package) that represents a date without a time component and without a time zone. It represents a date in the ISO calendar system (year, month, day). Since it does not store time information, it is suitable for scenarios where you need to deal with dates only, such as birthdays, anniversaries, and other date–based operations.
Key methods of the LocalDate
class:
now()
: Returns the current date based on the system clock and the default time zone.of(int year, int month, int dayOfMonth)
: Creates a LocalDate
instance with the specified year, month, and day.parse(CharSequence text)
: Parses a text string in the format “yyyy-MM-dd” to create a LocalDate
instance.getYear()
, getMonth()
, getDayOfMonth()
: Get the year, month, and day components of the LocalDate
.plusDays(long daysToAdd)
, plusMonths(long monthsToAdd)
, plusYears(long yearsToAdd)
: Add days, months, or years to the LocalDate
and return a new instance.minusDays(long daysToSubtract)
, minusMonths(long monthsToSubtract)
, minusYears(long yearsToSubtract)
: Subtract days, months, or years from the LocalDate
and return a new instance.// Create a LocalDate for the current date LocalDate currentDate = LocalDate.now(); System.out.println("Current Date: " + currentDate); // Create a LocalDate with a specific date LocalDate specificDate = LocalDate.of(2023, 7, 20); System.out.println("Specific Date: " + specificDate); // Parse a text string to create a LocalDate // Parses a text string in the format "yyyy-MM-dd" LocalDate parsedDate = LocalDate.parse("2023-07-20"); System.out.println("Parsed Date: " + parsedDate); // Get individual components of the LocalDate int year = specificDate.getYear(); int month = specificDate.getMonthValue(); int day = specificDate.getDayOfMonth(); System.out.println("Year: " + year + ", Month: " + month + ", Day: " + day); // Add or subtract days, months, or years LocalDate modifiedDate = specificDate.plusDays(5).minusMonths(1).plusYears(2); System.out.println("Modified Date: " + modifiedDate); // Check if a date comes before or after another date LocalDate futureDate = LocalDate.of(2024, 1, 1); if (futureDate.isAfter(specificDate)) { System.out.println("Future date is after specific date."); } else { System.out.println("Future date is not after specific date."); } // Check if a date is in the past LocalDate pastDate = LocalDate.of(2022, 1, 1); if (pastDate.isBefore(currentDate)) { System.out.println("Past date is before current date."); } else { System.out.println("Past date is not before current date."); }
Output
Current Date: 2023-07-23 Specific Date: 2023-07-20 Parsed Date: 2023-07-20 Year: 2023, Month: 7, Day: 20 Modified Date: 2025-06-25 Future date is after specific date. Past date is before current date.
LocalTime
LocalTime
is a class in the Java 8 Date and Time API (java.time
package) that represents a time of day without a date and time zone. It contains information about hours, minutes, seconds, and nanoseconds. LocalTime
is useful when you need to handle time-specific operations, such as setting reminders, scheduling events, or measuring time durations without considering the date.
Key methods of the LocalTime
class:
now()
: Returns the current time based on the system clock and the default time zone.of(int hour, int minute)
, of(int hour, int minute, int second)
, of(int hour, int minute, int second, int nanoOfSecond)
: Creates a LocalTime
instance with the specified hour, minute, second, and nanosecond.parse(CharSequence text)
: Parses a text string in the format “HH:mm:ss” or “HH:mm:ss.SSSSSSSSS” to create a LocalTime
instance.getHour()
, getMinute()
, getSecond()
, getNano()
: Get the hour, minute, second, and nanosecond components of the LocalTime
.plusHours(long hoursToAdd)
, plusMinutes(long minutesToAdd)
, plusSeconds(long secondsToAdd)
, plusNanos(long nanosToAdd)
: Add hours, minutes, seconds, or nanoseconds to the LocalTime
and return a new instance.minusHours(long hoursToSubtract)
, minusMinutes(long minutesToSubtract)
, minusSeconds(long secondsToSubtract)
, minusNanos(long nanosToSubtract)
: Subtract hours, minutes, seconds, or nanoseconds from the LocalTime
and return a new instance.// Create a LocalTime for the current time LocalTime currentTime = LocalTime.now(); System.out.println("Current Time: " + currentTime); // Create a LocalTime with a specific time LocalTime specificTime = LocalTime.of(12, 34); System.out.println("Specific Time: " + specificTime); // Create a LocalTime with a specific time including seconds and nanoseconds LocalTime specificTimeWithSeconds = LocalTime.of(12, 34, 56); System.out.println("Specific Time with Seconds: " + specificTimeWithSeconds); // Parse a text string to create a LocalTime LocalTime parsedTime = LocalTime.parse("13:45:30"); System.out.println("Parsed Time: " + parsedTime); // Get individual components of the LocalTime int hour = specificTime.getHour(); int minute = specificTime.getMinute(); int second = specificTimeWithSeconds.getSecond(); System.out.println("Hour: " + hour + ", Minute: " + minute + ", Second: " + second); // Add or subtract hours, minutes, seconds, or nanoseconds LocalTime modifiedTime = specificTime.plusHours(2).minusMinutes(15).plusSeconds(30).plusNanos(500000000); System.out.println("Modified Time: " + modifiedTime); // Check if a time comes before or after another time LocalTime futureTime = LocalTime.of(14, 0); if (futureTime.isAfter(specificTime)) { System.out.println("Future time is after specific time."); } else { System.out.println("Future time is not after specific time."); } // Check if a time is in the past LocalTime pastTime = LocalTime.of(11, 0); if (pastTime.isBefore(currentTime)) { System.out.println("Past time is before current time."); } else { System.out.println("Past time is not before current time."); }
Ouput
Current Time: 21:41:29.249370 Specific Time: 12:34 Specific Time with Seconds: 12:34:56 Parsed Time: 13:45:30 Hour: 12, Minute: 34, Second: 56 Modified Time: 14:19:30.500 Future time is after specific time. Past time is before current time.
ZonedDateTime
ZonedDateTime
is a class in the Java 8 Date and Time API (java.time
package) that represents a date and time in a specific time zone. It combines the functionalities of LocalDateTime
and ZoneId
to represent an instant in time with the time zone information. It allows you to perform operations that consider both the local date and time and the time zone.
// Get the current date and time in a specific time zone ZonedDateTime currentDateTime = ZonedDateTime.now(ZoneId.systemDefault()); System.out.println("Current Date and Time in New York: " + currentDateTime); // Create a ZonedDateTime for a specific date and time in a specific time zone ZonedDateTime specificDateTime = ZonedDateTime.of(2023, 7, 20, 12, 34, 56, 0, ZoneId.of("Asia/Tokyo")); System.out.println("Specific Date and Time in Tokyo: " + specificDateTime); // Convert a LocalDateTime to ZonedDateTime with a specified time zone ZonedDateTime convertedDateTime = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("Europe/London")); System.out.println("Converted Date and Time in London: " + convertedDateTime); // Convert a ZonedDateTime to an OffsetDateTime OffsetDateTime offsetDateTime = specificDateTime.toOffsetDateTime(); System.out.println("Offset Date and Time: " + offsetDateTime); // Get the time zone information from a ZonedDateTime ZoneId zoneId = specificDateTime.getZone(); System.out.println("Time Zone: " + zoneId); // Check if a ZonedDateTime occurs before or after another ZonedDateTime ZonedDateTime futureDateTime = specificDateTime.plusDays(1); if (futureDateTime.isAfter(specificDateTime)) { System.out.println("Future date is after specific date."); } else { System.out.println("Future date is not after specific date."); }
Output
Current Date and Time in New York: 2023-07-23T21:44:31.318829-06:00[America/Denver] Specific Date and Time in Tokyo: 2023-07-20T12:34:56+09:00[Asia/Tokyo] Converted Date and Time in London: 2023-07-23T21:44:31.319092+01:00[Europe/London] Offset Date and Time: 2023-07-20T12:34:56+09:00 Time Zone: Asia/Tokyo Future date is after specific date.
Duration
Duration
is a class in the java.time
package that represents a time-based duration. It measures the amount of time between two points in time in terms of hours, minutes, seconds, and nanoseconds. Duration
is primarily used to represent a duration between two instances of Instant
, but it can also be used with LocalTime
, LocalDateTime
, or any other time-based object that supports nanosecond precision.
Key points about Duration
:
Duration
is an immutable class, meaning once created, the value cannot be changed.Duration
class provides various methods for arithmetic operations like addition, subtraction, and multiplication with a scalar value.Duration.between(startInstant, endInstant)
to calculate the duration between two Instant
objects.Duration
provides the toMinutes()
, toHours()
, toDays()
, and other methods to convert the duration to different units.// Create a Duration between two Instants Instant start = Instant.now(); // Simulate some operation try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } Instant end = Instant.now(); Duration duration = Duration.between(start, end); System.out.println("Duration in seconds: " + duration.getSeconds()); System.out.println("Duration in milliseconds: " + duration.toMillis()); // Add and subtract duration Duration fiveMinutes = Duration.ofMinutes(5); Instant futureInstant = end.plus(fiveMinutes); Instant pastInstant = start.minus(fiveMinutes); System.out.println("Future Instant: " + futureInstant); System.out.println("Past Instant: " + pastInstant); // Compare durations Duration oneMinute = Duration.ofMinutes(1); Duration twoMinutes = Duration.ofMinutes(2); if (oneMinute.compareTo(twoMinutes) < 0) { System.out.println("One minute is less than two minutes."); } else if (oneMinute.compareTo(twoMinutes) > 0) { System.out.println("One minute is greater than two minutes."); } else { System.out.println("One minute is equal to two minutes."); } // Check if a duration is zero or negative Duration zeroDuration = Duration.ZERO; Duration negativeDuration = Duration.ofSeconds(-10); System.out.println("Is zero duration? " + zeroDuration.isZero()); System.out.println("Is negative duration? " + negativeDuration.isNegative());
Output
Duration in seconds: 2 Duration in milliseconds: 2003 Future Instant: 2023-07-24T03:54:47.283713Z Past Instant: 2023-07-24T03:44:45.280Z One minute is less than two minutes. Is zero duration? true Is negative duration? true
Period
Period
is a class in the java.time
package that represents a date-based period between two dates. It measures the difference between two LocalDate
instances in terms of years, months, and days. Period
is useful when you need to deal with date-based durations, such as calculating the difference between two dates, representing a period of time, or adding/subtracting time units to a date.
Key points about Period
:
Period
is an immutable class, meaning once created, the value cannot be changed.Period
class provides various methods for arithmetic operations like addition, subtraction, and multiplication with a scalar value.Period.between(startDate, endDate)
to calculate the period between two LocalDate
objects.Period
provides the getYears()
, getMonths()
, getDays()
, and other methods to access individual components of the period.// Create a Period between two LocalDates LocalDate startDate = LocalDate.of(2023, 7, 1); LocalDate endDate = LocalDate.of(2023, 12, 31); Period period = Period.between(startDate, endDate); System.out.println("Period: " + period); System.out.println("Years: " + period.getYears()); System.out.println("Months: " + period.getMonths()); System.out.println("Days: " + period.getDays()); // Add and subtract periods Period threeMonths = Period.ofMonths(3); LocalDate futureDate = endDate.plus(threeMonths); LocalDate pastDate = startDate.minus(threeMonths); System.out.println("Future Date: " + futureDate); System.out.println("Past Date: " + pastDate); // Check if a period is zero or negative Period zeroPeriod = Period.ZERO; Period negativePeriod = Period.ofYears(-1); System.out.println("Is zero period? " + zeroPeriod.isZero()); System.out.println("Is negative period? " + negativePeriod.isNegative());
Output
Period: P5M30D Years: 0 Months: 5 Days: 30 Future Date: 2024-03-31 Past Date: 2023-04-01 Is zero period? true Is negative period? true
We demonstrated how to create and use Period
objects. We calculated the period between two LocalDate
objects using Period.between()
, performed arithmetic operations like addition and subtraction, and compared two Period
objects. We also checked if a period is zero or negative using the isZero()
and isNegative()
methods.
Period
is a useful class when you need to work with date-based durations, and it can simplify date-related calculations and logic in your Java applications
The class Date epresents a specific instant in time, with millisecond precision.
Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false.
Date today = DateUtils.addDays(new Date(), 0); Date yesterday = DateUtils.addDays(new Date(), -1); System.out.println("today - " + today.toInstant().toString()); System.out.println("yesterday - " + yesterday.toInstant().toString()); System.out.println("today.after(yesterday) - " + today.after(yesterday)); System.out.println("today.equals(yesterday) - " + today.equals(yesterday)); System.out.println("yesterday.after(today) - " + yesterday.after(today)); // Output today - 2020-10-02T04:34:35.465Z yesterday - 2020-10-01T04:34:35.480Z today.after(yesterday) - true today.equals(yesterday) - false yesterday.after(today) - false
Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false.
Date today = DateUtils.addDays(new Date(), 0); Date yesterday = DateUtils.addDays(new Date(), -1); System.out.println("today - " + today.toInstant().toString()); System.out.println("yesterday - " + yesterday.toInstant().toString()); System.out.println("today.before(yesterday) - " + today.before(yesterday)); System.out.println("today.equals(yesterday) - " + today.equals(yesterday)); System.out.println("yesterday.before(today) - " + yesterday.before(today)); // output today - 2020-10-02T15:48:24.823Z yesterday - 2020-10-01T15:48:24.837Z today.before(yesterday) - false today.equals(yesterday) - false yesterday.before(today) - true
Check if same two dates are the same day
/** * Check if day1 is the same day as day2<br/> * day1 - 2020-6-12, day2 - 2020-6-13, return false <br/> * day1 - 2020-6-12, day2 - 2020-6-12, return false <br/> * day1 - 2020-6-13, day2 - 2020-6-12, return false <br/> */ public static boolean isSameDay(Date day1, Date day2) { if (day1 == null || day2 == null) { return false; } final Calendar cal1 = Calendar.getInstance(); cal1.setTime(day1); final Calendar cal2 = Calendar.getInstance(); cal2.setTime(day2); return cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) && cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH); }
Check if day1 is after day2
/** * Check if day1 is after day2<br/> * day1 - 2020-6-12, day2 - 2020-6-13, return false <br/> * day1 - 2020-6-12, day2 - 2020-6-12, return false <br/> * day1 - 2020-6-13, day2 - 2020-6-12, return true <br/> */ public static boolean isAfterDay(Date day1, Date day2) { if (day1 == null || day2 == null) { return false; } final Calendar cal1 = Calendar.getInstance(); cal1.setTime(day1); final Calendar cal2 = Calendar.getInstance(); cal2.setTime(day2); if (cal1.get(Calendar.YEAR) < cal2.get(Calendar.YEAR)) { return false; } else if (cal1.get(Calendar.MONTH) < cal2.get(Calendar.MONTH)) { return false; } else if (cal1.get(Calendar.DAY_OF_MONTH) <= cal2.get(Calendar.DAY_OF_MONTH)) { return false; } return true; }
Check if day1 is before day2
/** * Check if day1 is before day2<br/> * day1 - 2020-6-12, day2 - 2020-6-13, return true <br/> * day1 - 2020-6-12, day2 - 2020-6-12, return false <br/> * day1 - 2020-6-13, day2 - 2020-6-12, return false <br/> */ public static boolean isBeforeDay(Date day1, Date day2) { if (day1 == null || day2 == null) { return false; } final Calendar cal1 = Calendar.getInstance(); cal1.setTime(day1); final Calendar cal2 = Calendar.getInstance(); cal2.setTime(day2); if (cal1.get(Calendar.YEAR) > cal2.get(Calendar.YEAR)) { return false; } else if (cal1.get(Calendar.MONTH) > cal2.get(Calendar.MONTH)) { return false; } else if (cal1.get(Calendar.DAY_OF_MONTH) >= cal2.get(Calendar.DAY_OF_MONTH)) { return false; } return true; }