← Back to list

Understanding Java’s Date and Time API: A Detailed Exploration of java.time

In Java, the java.time package introduced in Java 8 provides a comprehensive set of classes to work with date and time. These classes are…

Vinotech · 2024-09-25 06:29 · 10 claps · 17.8 min read paywalled
#java-date-time #localdatetime #zonaldatetime #zoneid #java
Open on Medium ↗
Wiki topics: FT · Fine-tuning & Adaptation

Understanding Java’s Date and Time API: A Detailed Exploration of java.time Classes with Practical Examples

In Java, the java.time package introduced in Java 8 provides a comprehensive set of classes to work with date and time. These classes are part of the new Date and Time API, and they are immutable and thread-safe, unlike the older java.util.Date and java.util.Calendar classes.

**In this article, topics are covered. **👇

  1. LocalDate, LocalTime, LocalDateTime
  2. ZonedDateTime, ZoneId, and ZoneOffset
  3. OffsetDateTime and OffsetTime
  4. Period Class
  5. TemporalAdjusters, TemporalUnit, TemporalAmount

Here is a list of important classes in the java.time package related to date and time handling:

1. LocalDate

LocalDate is a class in Java that is part of the java.time package, introduced in Java 8. It represents a date without a time-zone in the ISO-8601 calendar system, such as 2023-10-05. This class provides various methods to manipulate and query dates.

Here are some common examples of using LocalDate:

  1. Creating a LocalDate
import java.time.LocalDate;

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, 10, 5);
        System.out.println("Specific Date: " + specificDate);

        // Parsing a date from a string
        LocalDate parsedDate = LocalDate.parse("2023-10-05");
        System.out.println("Parsed Date: " + parsedDate);
    }
}

output : 
Current Date: 2024-09-25 
Specific Date: 2023-10-05
Parsed Date: 2023-10-05

2. Getting Date Components

public class LocalDateExample {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2023, 10, 5);

        int year = date.getYear();
        int month = date.getMonthValue();
        int day = date.getDayOfMonth();

        System.out.println("Year: " + year);
        System.out.println("Month: " + month);
        System.out.println("Day: " + day);
    }
}

output :
Year: 2023
Month: 10
Day: 5

4. Comparing Dates

public class LocalDateExample {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.of(2023, 10, 5);
        LocalDate date2 = LocalDate.of(2023, 11, 5);

        if (date1.isBefore(date2)) {
            System.out.println(date1 + " is before " + date2);
        }

        if (date1.isAfter(date2)) {
            System.out.println(date1 + " is after " + date2);
        }

        if (date1.isEqual(date2)) {
            System.out.println(date1 + " is equal to " + date2);
        }
    }
}

Output : 
2023-10-05 is before 2023-11-05

5. Formatting Dates

import java.time.format.DateTimeFormatter;

public class LocalDateExample {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2023, 10, 5);

        // Custom formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
        String formattedDate = date.format(formatter);
        System.out.println("Formatted Date: " + formattedDate);
    }
}

Output : 
Formatted Date: 05-10-2023

6. Calculating the Difference Between Dates

import java.time.temporal.ChronoUnit;

public class LocalDateExample {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.of(2023, 10, 5);
        LocalDate date2 = LocalDate.of(2023, 11, 5);

        long daysBetween = ChronoUnit.DAYS.between(date1, date2);
        System.out.println("Days between dates: " + daysBetween);

        long monthsBetween = ChronoUnit.MONTHS.between(date1, date2);
        System.out.println("Months between dates: " + monthsBetween);
    }
}

Output : 
Days between dates: 31
Months between dates: 1

2. LocalTime LocalTime is a class in Java that is part of the java.time package, introduced in Java 8. It represents a time without a date and without a time-zone in the ISO-8601 calendar system, such as 14:30:00. This class provides various methods to manipulate and query times.

Here are some common examples of using LocalTime, along with their expected outputs:

1. Creating a LocalTime

import java.time.LocalTime;

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(14, 30);
        System.out.println("Specific Time: " + specificTime);

        // Parsing a time from a string
        LocalTime parsedTime = LocalTime.parse("14:30:00");
        System.out.println("Parsed Time: " + parsedTime);
    }
}

Output:
Current Time: 12:34:56.789  // This will be the current system time
Specific Time: 14:30
Parsed Time: 14:30

2. Getting Time Components

public class LocalTimeExample {
    public static void main(String[] args) {
        LocalTime time = LocalTime.of(14, 30, 45);

        int hour = time.getHour();
        int minute = time.getMinute();
        int second = time.getSecond();

        System.out.println("Hour: " + hour);
        System.out.println("Minute: " + minute);
        System.out.println("Second: " + second);
    }
}

Output:
Hour: 14
Minute: 30
Second: 45

3. Adding and Subtracting Times

public class LocalTimeExample {
    public static void main(String[] args) {
        LocalTime time = LocalTime.of(14, 30);

        // Adding hours
        LocalTime newTime = time.plusHours(2);
        System.out.println("Time after adding 2 hours: " + newTime);

        // Subtracting minutes
        newTime = time.minusMinutes(15);
        System.out.println("Time after subtracting 15 minutes: " + newTime);
    }
}

Output:
Time after adding 2 hours: 16:30
Time after subtracting 15 minutes: 14:15

4. Comparing Times

public class LocalTimeExample {
    public static void main(String[] args) {
        LocalTime time1 = LocalTime.of(14, 30);
        LocalTime time2 = LocalTime.of(15, 30);

        if (time1.isBefore(time2)) {
            System.out.println(time1 + " is before " + time2);
        }

        if (time1.isAfter(time2)) {
            System.out.println(time1 + " is after " + time2);
        }

        if (time1.equals(time2)) {
            System.out.println(time1 + " is equal to " + time2);
        }
    }
}

Output:
14:30 is before 15:30

5. Formatting Times

import java.time.format.DateTimeFormatter;

public class LocalTimeExample {
    public static void main(String[] args) {
        LocalTime time = LocalTime.of(14, 30);

        // Custom formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        String formattedTime = time.format(formatter);
        System.out.println("Formatted Time: " + formattedTime);
    }
}

Output:
Formatted Time: 14:30:00

6. Calculating the Difference Between Times

import java.time.temporal.ChronoUnit;

public class LocalTimeExample {
    public static void main(String[] args) {
        LocalTime time1 = LocalTime.of(14, 30);
        LocalTime time2 = LocalTime.of(15, 30);

        long hoursBetween = ChronoUnit.HOURS.between(time1, time2);
        System.out.println("Hours between times: " + hoursBetween);

        long minutesBetween = ChronoUnit.MINUTES.between(time1, time2);
        System.out.println("Minutes between times: " + minutesBetween);
    }
}

Output:
Hours between times: 1
Minutes between times: 60
  1. LocalDateTime LocalDateTime is a class in Java that is part of the java.time package, introduced in Java 8. It represents a date-time without a time-zone in the ISO-8601 calendar system, such as 2023-10-05T14:30:00. This class provides various methods to manipulate and query date-times.

Here are some common examples of using LocalDateTime, along with their expected outputs:

1. Creating a LocalDateTime

import java.time.LocalDateTime;

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, 10, 5, 14, 30);
        System.out.println("Specific Date-Time: " + specificDateTime);

        // Parsing a date-time from a string
        LocalDateTime parsedDateTime = LocalDateTime.parse("2023-10-05T14:30:00");
        System.out.println("Parsed Date-Time: " + parsedDateTime);
    }
}

Output:
Current Date-Time: 2023-10-05T12:34:56.789  // This will be the current system date-time
Specific Date-Time: 2023-10-05T14:30
Parsed Date-Time: 2023-10-05T14:30

2. Getting Date-Time Components

public class LocalDateTimeExample {
    public static void main(String[] args) {
        LocalDateTime dateTime = LocalDateTime.of(2023, 10, 5, 14, 30, 45);

        int year = dateTime.getYear();
        int month = dateTime.getMonthValue();
        int day = dateTime.getDayOfMonth();
        int hour = dateTime.getHour();
        int minute = dateTime.getMinute();
        int second = dateTime.getSecond();

        System.out.println("Year: " + year);
        System.out.println("Month: " + month);
        System.out.println("Day: " + day);
        System.out.println("Hour: " + hour);
        System.out.println("Minute: " + minute);
        System.out.println("Second: " + second);
    }
}

Output:
Year: 2023
Month: 10
Day: 5
Hour: 14
Minute: 30
Second: 45

3. Adding and Subtracting Date-Times

public class LocalDateTimeExample {
    public static void main(String[] args) {
        LocalDateTime dateTime = LocalDateTime.of(2023, 10, 5, 14, 30);

        // Adding days
        LocalDateTime newDateTime = dateTime.plusDays(2);
        System.out.println("Date-Time after adding 2 days: " + newDateTime);

        // Subtracting hours
        newDateTime = dateTime.minusHours(1);
        System.out.println("Date-Time after subtracting 1 hour: " + newDateTime);
    }
}

Output:
Date-Time after adding 2 days: 2023-10-07T14:30
Date-Time after subtracting 1 hour: 2023-10-05T13:30

4. Comparing Date-Times

public class LocalDateTimeExample {
    public static void main(String[] args) {
        LocalDateTime dateTime1 = LocalDateTime.of(2023, 10, 5, 14, 30);
        LocalDateTime dateTime2 = LocalDateTime.of(2023, 10, 5, 15, 30);

        if (dateTime1.isBefore(dateTime2)) {
            System.out.println(dateTime1 + " is before " + dateTime2);
        }

        if (dateTime1.isAfter(dateTime2)) {
            System.out.println(dateTime1 + " is after " + dateTime2);
        }

        if (dateTime1.isEqual(dateTime2)) {
            System.out.println(dateTime1 + " is equal to " + dateTime2);
        }
    }
}

Output:
2023-10-05T14:30 is before 2023-10-05T15:30

5. Formatting Date-Times

import java.time.format.DateTimeFormatter;

public class LocalDateTimeExample {
    public static void main(String[] args) {
        LocalDateTime dateTime = LocalDateTime.of(2023, 10, 5, 14, 30);

        // Custom formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = dateTime.format(formatter);
        System.out.println("Formatted Date-Time: " + formattedDateTime);
    }
}

Output:
Formatted Date-Time: 2023-10-05 14:30:00

6. Calculating the Difference Between Date-Times

import java.time.temporal.ChronoUnit;

public class LocalDateTimeExample {
    public static void main(String[] args) {
        LocalDateTime dateTime1 = LocalDateTime.of(2023, 10, 5, 14, 30);
        LocalDateTime dateTime2 = LocalDateTime.of(2023, 10, 5, 15, 30);

        long hoursBetween = ChronoUnit.HOURS.between(dateTime1, dateTime2);
        System.out.println("Hours between date-times: " + hoursBetween);

        long minutesBetween = ChronoUnit.MINUTES.between(dateTime1, dateTime2);
        System.out.println("Minutes between date-times: " + minutesBetween);
    }
}

Output:
Hours between date-times: 1
Minutes between date-times: 60

7. Extracting Date and Time

import java.time.LocalDate;
import java.time.LocalTime;

public class LocalDateTimeExample {
    public static void main(String[] args) {
        LocalDateTime dateTime = LocalDateTime.of(2023, 10, 5, 14, 30);

        LocalDate date = dateTime.toLocalDate();
        LocalTime time = dateTime.toLocalTime();

        System.out.println("Date: " + date);
        System.out.println("Time: " + time);
    }
}

Output:
Date: 2023-10-05
Time: 14:30

4. ZonedDateTime, ZoneId, and ZoneOffset ZonedDateTime, ZoneId, and ZoneOffset are classes in Java that are part of the java.time package, introduced in Java 8. They provide support for working with date-times that include time-zone information.

ZonedDateTime

ZonedDateTime represents a date-time with a time-zone in the ISO-8601 calendar system, such as 2023-10-05T14:30:00+02:00[Europe/Paris].

ZoneId

ZoneId represents a time-zone region, such as Europe/Paris or America/New_York.

ZoneOffset

ZoneOffset represents the amount of time to add to or subtract from UTC, such as +02:00.

Here are some common examples of using ZonedDateTime, ZoneId, and ZoneOffset, along with their expected outputs:

1. Creating a ZonedDateTime

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class ZonedDateTimeExample {
    public static void main(String[] args) {
        // Current date-time with system default time-zone
        ZonedDateTime currentDateTime = ZonedDateTime.now();
        System.out.println("Current Date-Time: " + currentDateTime);

        // Specific date-time with a specific time-zone
        LocalDateTime localDateTime = LocalDateTime.of(2023, 10, 5, 14, 30);
        ZoneId zoneId = ZoneId.of("Europe/Paris");
        ZonedDateTime specificDateTime = ZonedDateTime.of(localDateTime, zoneId);
        System.out.println("Specific Date-Time: " + specificDateTime);

        // Parsing a date-time from a string with a time-zone
        ZonedDateTime parsedDateTime = ZonedDateTime.parse("2023-10-05T14:30:00+02:00[Europe/Paris]");
        System.out.println("Parsed Date-Time: " + parsedDateTime);
    }
}

Output : 
Current Date-Time: 2023-10-05T12:34:56.789Z[SystemV/EST5EDT]  // This will be the current system date-time with time-zone
Specific Date-Time: 2023-10-05T14:30+02:00[Europe/Paris]
Parsed Date-Time: 2023-10-05T14:30+02:00[Europe/Paris]

2. Getting Date-Time Components

public class ZonedDateTimeExample {
    public static void main(String[] args) {
        ZonedDateTime dateTime = ZonedDateTime.of(LocalDateTime.of(2023, 10, 5, 14, 30), ZoneId.of("Europe/Paris"));

        int year = dateTime.getYear();
        int month = dateTime.getMonthValue();
        int day = dateTime.getDayOfMonth();
        int hour = dateTime.getHour();
        int minute = dateTime.getMinute();
        int second = dateTime.getSecond();
        ZoneId zoneId = dateTime.getZone();

        System.out.println("Year: " + year);
        System.out.println("Month: " + month);
        System.out.println("Day: " + day);
        System.out.println("Hour: " + hour);
        System.out.println("Minute: " + minute);
        System.out.println("Second: " + second);
        System.out.println("ZoneId: " + zoneId);
    }
}

Output : 
Year: 2023
Month: 10
Day: 5
Hour: 14
Minute: 30
Second: 0
ZoneId: Europe/Paris

3. Adding and Subtracting Date-Times with Time-Zones

public class ZonedDateTimeExample {
    public static void main(String[] args) {
        ZonedDateTime dateTime = ZonedDateTime.of(LocalDateTime.of(2023, 10, 5, 14, 30), ZoneId.of("Europe/Paris"));

        // Adding days
        ZonedDateTime newDateTime = dateTime.plusDays(2);
        System.out.println("Date-Time after adding 2 days: " + newDateTime);

        // Subtracting hours
        newDateTime = dateTime.minusHours(1);
        System.out.println("Date-Time after subtracting 1 hour: " + newDateTime);
    }
}

Output :
Date-Time after adding 2 days: 2023-10-07T14:30+02:00[Europe/Paris]
Date-Time after subtracting 1 hour: 2023-10-05T13:30+02:00[Europe/Paris]

4. Comparing Date-Times with Time-Zones

public class ZonedDateTimeExample {
    public static void main(String[] args) {
        ZonedDateTime dateTime1 = ZonedDateTime.of(LocalDateTime.of(2023, 10, 5, 14, 30), ZoneId.of("Europe/Paris"));
        ZonedDateTime dateTime2 = ZonedDateTime.of(LocalDateTime.of(2023, 10, 5, 15, 30), ZoneId.of("Europe/Paris"));

        if (dateTime1.isBefore(dateTime2)) {
            System.out.println(dateTime1 + " is before " + dateTime2);
        }

        if (dateTime1.isAfter(dateTime2)) {
            System.out.println(dateTime1 + " is after " + dateTime2);
        }

        if (dateTime1.isEqual(dateTime2)) {
            System.out.println(dateTime1 + " is equal to " + dateTime2);
        }
    }
}

Output : 
2023-10-05T14:30+02:00[Europe/Paris] is before 2023-10-05T15:30+02:00[Europe/Paris]

5. Formatting Date-Times with Time-Zones

import java.time.format.DateTimeFormatter;

public class ZonedDateTimeExample {
    public static void main(String[] args) {
        ZonedDateTime dateTime = ZonedDateTime.of(LocalDateTime.of(2023, 10, 5, 14, 30), ZoneId.of("Europe/Paris"));

        // Custom formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
        String formattedDateTime = dateTime.format(formatter);
        System.out.println("Formatted Date-Time: " + formattedDateTime);
    }
}

Output :
Formatted Date-Time: 2023-10-05 14:30:00 CEST

6. Calculating the Difference Between Date-Times with Time-Zones

import java.time.temporal.ChronoUnit;

public class ZonedDateTimeExample {
    public static void main(String[] args) {
        ZonedDateTime dateTime1 = ZonedDateTime.of(LocalDateTime.of(2023, 10, 5, 14, 30), ZoneId.of("Europe/Paris"));
        ZonedDateTime dateTime2 = ZonedDateTime.of(LocalDateTime.of(2023, 10, 5, 15, 30), ZoneId.of("Europe/Paris"));

        long hoursBetween = ChronoUnit.HOURS.between(dateTime1, dateTime2);
        System.out.println("Hours between date-times: " + hoursBetween);

        long minutesBetween = ChronoUnit.MINUTES.between(dateTime1, dateTime2);
        System.out.println("Minutes between date-times: " + minutesBetween);
    }
}

Output : 
Hours between date-times: 1
Minutes between date-times: 60

7. Working with ZoneId

import java.util.Set;

public class ZoneIdExample {
    public static void main(String[] args) {
        // Getting the system default time-zone
        ZoneId systemZoneId = ZoneId.systemDefault();
        System.out.println("System Default ZoneId: " + systemZoneId);

        // Getting a specific time-zone
        ZoneId specificZoneId = ZoneId.of("Europe/Paris");
        System.out.println("Specific ZoneId: " + specificZoneId);

        // Getting all available time-zones
        Set<String> allZoneIds = ZoneId.getAvailableZoneIds();
        System.out.println("All ZoneIds: " + allZoneIds);
    }
}

Output : 
System Default ZoneId: America/New_York  // This will be the system default time-zone
Specific ZoneId: Europe/Paris
All ZoneIds: [Africa/Abidjan, Africa/Accra, Africa/Addis_Ababa, ...]  // This will list all available time-zones

8. Working with ZoneOffset

import java.time.ZoneOffset;

public class ZoneOffsetExample {
    public static void main(String[] args) {
        // Creating a specific zone offset
        ZoneOffset offset = ZoneOffset.of("+02:00");
        System.out.println("ZoneOffset: " + offset);

        // Getting the total seconds of the offset
        int totalSeconds = offset.getTotalSeconds();
        System.out.println("Total Seconds: " + totalSeconds);
    }
}

Output : 
ZoneOffset: +02:00
Total Seconds: 7200

5. OffsetDateTime and OffsetTime OffsetDateTime and OffsetTime are classes in Java that are part of the java.time package, introduced in Java 8. They represent date-times and times with an offset from UTC, respectively, without reference to a specific time-zone region.

OffsetDateTime

OffsetDateTime represents a date-time with an offset from UTC, such as 2023-10-05T14:30:00+02:00. This class is useful when you need to work with date-times that include an offset but do not need the full time-zone information.

OffsetTime

OffsetTime represents a time with an offset from UTC, such as 14:30:00+02:00. This class is useful when you need to work with times that include an offset but do not need the full time-zone information.

Here are some common examples of using OffsetDateTime and OffsetTime, along with their expected outputs:

1. Creating an OffsetDateTime

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class OffsetDateTimeExample {
    public static void main(String[] args) {
        // Current date-time with system default offset
        OffsetDateTime currentDateTime = OffsetDateTime.now();
        System.out.println("Current Date-Time: " + currentDateTime);

        // Specific date-time with a specific offset
        LocalDateTime localDateTime = LocalDateTime.of(2023, 10, 5, 14, 30);
        ZoneOffset offset = ZoneOffset.of("+02:00");
        OffsetDateTime specificDateTime = OffsetDateTime.of(localDateTime, offset);
        System.out.println("Specific Date-Time: " + specificDateTime);

        // Parsing a date-time from a string with an offset
        OffsetDateTime parsedDateTime = OffsetDateTime.parse("2023-10-05T14:30:00+02:00");
        System.out.println("Parsed Date-Time: " + parsedDateTime);
    }
}

Output : 
Current Date-Time: 2023-10-05T12:34:56.789Z  // This will be the current system date-time with offset
Specific Date-Time: 2023-10-05T14:30+02:00
Parsed Date-Time: 2023-10-05T14:30+02:00

2. Creating an OffsetTime

import java.time.LocalTime;
import java.time.OffsetTime;
import java.time.ZoneOffset;

public class OffsetTimeExample {
    public static void main(String[] args) {
        // Current time with system default offset
        OffsetTime currentTime = OffsetTime.now();
        System.out.println("Current Time: " + currentTime);

        // Specific time with a specific offset
        LocalTime localTime = LocalTime.of(14, 30);
        ZoneOffset offset = ZoneOffset.of("+02:00");
        OffsetTime specificTime = OffsetTime.of(localTime, offset);
        System.out.println("Specific Time: " + specificTime);

        // Parsing a time from a string with an offset
        OffsetTime parsedTime = OffsetTime.parse("14:30:00+02:00");
        System.out.println("Parsed Time: " + parsedTime);
    }
}

Output: 
Current Time: 12:34:56.789Z  // This will be the current system time with offset
Specific Time: 14:30+02:00
Parsed Time: 14:30+02:00

3. Getting Date-Time and Time Components

OffsetDateTime

public class OffsetDateTimeExample {
    public static void main(String[] args) {
        OffsetDateTime dateTime = OffsetDateTime.of(LocalDateTime.of(2023, 10, 5, 14, 30), ZoneOffset.of("+02:00"));

        int year = dateTime.getYear();
        int month = dateTime.getMonthValue();
        int day = dateTime.getDayOfMonth();
        int hour = dateTime.getHour();
        int minute = dateTime.getMinute();
        int second = dateTime.getSecond();
        ZoneOffset offset = dateTime.getOffset();

        System.out.println("Year: " + year);
        System.out.println("Month: " + month);
        System.out.println("Day: " + day);
        System.out.println("Hour: " + hour);
        System.out.println("Minute: " + minute);
        System.out.println("Second: " + second);
        System.out.println("Offset: " + offset);
    }
}

Output : 
Year: 2023
Month: 10
Day: 5
Hour: 14
Minute: 30
Second: 0
Offset: +02:00

OffsetTime

public class OffsetTimeExample {
    public static void main(String[] args) {
        OffsetTime time = OffsetTime.of(LocalTime.of(14, 30), ZoneOffset.of("+02:00"));

        int hour = time.getHour();
        int minute = time.getMinute();
        int second = time.getSecond();
        ZoneOffset offset = time.getOffset();

        System.out.println("Hour: " + hour);
        System.out.println("Minute: " + minute);
        System.out.println("Second: " + second);
        System.out.println("Offset: " + offset);
    }
}

Output : 
Hour: 14
Minute: 30
Second: 0
Offset: +02:00

4. Adding and Subtracting Date-Times and Times with Offsets

OffsetDateTime

public class OffsetDateTimeExample {
    public static void main(String[] args) {
        OffsetDateTime dateTime = OffsetDateTime.of(LocalDateTime.of(2023, 10, 5, 14, 30), ZoneOffset.of("+02:00"));

        // Adding days
        OffsetDateTime newDateTime = dateTime.plusDays(2);
        System.out.println("Date-Time after adding 2 days: " + newDateTime);

        // Subtracting hours
        newDateTime = dateTime.minusHours(1);
        System.out.println("Date-Time after subtracting 1 hour: " + newDateTime);
    }
}

Output : 
Date-Time after adding 2 days: 2023-10-07T14:30+02:00
Date-Time after subtracting 1 hour: 2023-10-05T13:30+02:00

OffsetTime

public class OffsetTimeExample {
    public static void main(String[] args) {
        OffsetTime time = OffsetTime.of(LocalTime.of(14, 30), ZoneOffset.of("+02:00"));

        // Adding minutes
        OffsetTime newTime = time.plusMinutes(15);
        System.out.println("Time after adding 15 minutes: " + newTime);

        // Subtracting hours
        newTime = time.minusHours(1);
        System.out.println("Time after subtracting 1 hour: " + newTime);
    }
}

Output : 
Time after adding 15 minutes: 14:45+02:00
Time after subtracting 1 hour: 13:30+02:00

5. Comparing Date-Times and Times with Offsets

OffsetDateTime

public class OffsetDateTimeExample {
    public static void main(String[] args) {
        OffsetDateTime dateTime1 = OffsetDateTime.of(LocalDateTime.of(2023, 10, 5, 14, 30), ZoneOffset.of("+02:00"));
        OffsetDateTime dateTime2 = OffsetDateTime.of(LocalDateTime.of(2023, 10, 5, 15, 30), ZoneOffset.of("+02:00"));

        if (dateTime1.isBefore(dateTime2)) {
            System.out.println(dateTime1 + " is before " + dateTime2);
        }

        if (dateTime1.isAfter(dateTime2)) {
            System.out.println(dateTime1 + " is after " + dateTime2);
        }

        if (dateTime1.isEqual(dateTime2)) {
            System.out.println(dateTime1 + " is equal to " + dateTime2);
        }
    }
}

Output
2023-10-05T14:30+02:00 is before 2023-10-05T15:30+02:00

OffsetTime

public class OffsetTimeExample {
    public static void main(String[] args) {
        OffsetTime time1 = OffsetTime.of(LocalTime.of(14, 30), ZoneOffset.of("+02:00"));
        OffsetTime time2 = OffsetTime.of(LocalTime.of(15, 30), ZoneOffset.of("+02:00"));

        if (time1.isBefore(time2)) {
            System.out.println(time1 + " is before " + time2);
        }

        if (time1.isAfter(time2)) {
            System.out.println(time1 + " is after " + time2);
        }

        if (time1.equals(time2)) {
            System.out.println(time1 + " is equal to " + time2);
        }
    }
}

Output : 
14:30+02:00 is before 15:30+02:00

6. Formatting Date-Times and Times with Offsets

OffsetDateTime

import java.time.format.DateTimeFormatter;

public class OffsetDateTimeExample {
    public static void main(String[] args) {
        OffsetDateTime dateTime = OffsetDateTime.of(LocalDateTime.of(2023, 10, 5, 14, 30), ZoneOffset.of("+02:00"));

        // Custom formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss XXX");
        String formattedDateTime = dateTime.format(formatter);
        System.out.println("Formatted Date-Time: " + formattedDateTime);
    }
}

Output : 
Formatted Date-Time: 2023-10-05 14:30:00 +02:00

OffsetTime

import java.time.format.DateTimeFormatter;

public class OffsetTimeExample {
    public static void main(String[] args) {
        OffsetTime time = OffsetTime.of(LocalTime.of(14, 30), ZoneOffset.of("+02:00"));

        // Custom formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss XXX");
        String formattedTime = time.format(formatter);
        System.out.println("Formatted Time: " + formattedTime);
    }
}

output : 
Formatted Time: 14:30:00 +02:00

7. Calculating the Difference Between Date-Times and Times with Offsets

OffsetDateTime

import java.time.temporal.ChronoUnit;

public class OffsetDateTimeExample {
    public static void main(String[] args) {
        OffsetDateTime dateTime1 = OffsetDateTime.of(LocalDateTime.of(2023, 10, 5, 14, 30), ZoneOffset.of("+02:00"));
        OffsetDateTime dateTime2 = OffsetDateTime.of(LocalDateTime.of(2023, 10, 5, 15, 30), ZoneOffset.of("+02:00"));

        long hoursBetween = ChronoUnit.HOURS.between(dateTime1, dateTime2);
        System.out.println("Hours between date-times: " + hoursBetween);

        long minutesBetween = ChronoUnit.MINUTES.between(dateTime1, dateTime2);
        System.out.println("Minutes between date-times: " + minutesBetween);
    }
}

output : 
Hours between date-times: 1
Minutes between date-times: 60

OffsetTime

import java.time.temporal.ChronoUnit;

public class OffsetTimeExample {
    public static void main(String[] args) {
        OffsetTime time1 = OffsetTime.of(LocalTime.of(14, 30), ZoneOffset.of("+02:00"));
        OffsetTime time2 = OffsetTime.of(LocalTime.of(15, 30), ZoneOffset.of("+02:00"));

        long hoursBetween = ChronoUnit.HOURS.between(time1, time2);
        System.out.println("Hours between times: " + hoursBetween);

        long minutesBetween = ChronoUnit.MINUTES.between(time1, time2);
        System.out.println("Minutes between times: " + minutesBetween);
    }
}

Output : 
Hours between times: 1
Minutes between times: 60

Period

Period is a class in Java that is part of the java.time package, introduced in Java 8. It represents a date-based amount of time, such as "3 years, 2 months, and 5 days". This class is useful for performing date arithmetic and manipulating dates.

Here are some common examples of using Period, along with their expected outputs:

1. Creating a Period

import java.time.Period;

public class PeriodExample {
    public static void main(String[] args) {
        // Creating a period of 3 years, 2 months, and 5 days
        Period period = Period.of(3, 2, 5);
        System.out.println("Period: " + period);

        // Creating a period of 2 months
        Period periodMonths = Period.ofMonths(2);
        System.out.println("Period (Months): " + periodMonths);

        // Creating a period of 5 days
        Period periodDays = Period.ofDays(5);
        System.out.println("Period (Days): " + periodDays);

        // Parsing a period from a string
        Period parsedPeriod = Period.parse("P3Y2M5D");
        System.out.println("Parsed Period: " + parsedPeriod);
    }
}

Output : 
Period: P3Y2M5D
Period (Months): P2M
Period (Days): P5D
Parsed Period: P3Y2M5D

2. Getting Period Components

public class PeriodExample {
    public static void main(String[] args) {
        Period period = Period.of(3, 2, 5);

        int years = period.getYears();
        int months = period.getMonths();
        int days = period.getDays();

        System.out.println("Years: " + years);
        System.out.println("Months: " + months);
        System.out.println("Days: " + days);
    }
}

output : 
Years: 3
Months: 2
Days: 5

3. Adding and Subtracting Periods

import java.time.LocalDate;

public class PeriodExample {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2023, 10, 5);
        Period period = Period.of(3, 2, 5);

        // Adding a period to a date
        LocalDate newDate = date.plus(period);
        System.out.println("Date after adding period: " + newDate);

        // Subtracting a period from a date
        newDate = date.minus(period);
        System.out.println("Date after subtracting period: " + newDate);
    }
}

Output
Date after adding period: 2026-12-10
Date after subtracting period: 2020-07-30

4. Comparing Periods

public class PeriodExample {
    public static void main(String[] args) {
        Period period1 = Period.of(3, 2, 5);
        Period period2 = Period.of(2, 5, 10);

        if (period1.isZero()) {
            System.out.println("Period1 is zero");
        }

        if (period1.isNegative()) {
            System.out.println("Period1 is negative");
        }

        if (period1.equals(period2)) {
            System.out.println("Period1 is equal to Period2");
        } else {
            System.out.println("Period1 is not equal to Period2");
        }
    }
}

Output : 
Period1 is not equal to Period2

5. Formatting Periods

public class PeriodExample {
    public static void main(String[] args) {
        Period period = Period.of(3, 2, 5);

        // Custom formatter
        String formattedPeriod = String.format("P%dY%dM%dD", period.getYears(), period.getMonths(), period.getDays());
        System.out.println("Formatted Period: " + formattedPeriod);
    }
}

Output : 
Formatted Period: P3Y2M5D

6. Calculating the Difference Between Dates as a Period

import java.time.temporal.ChronoUnit;

public class PeriodExample {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.of(2023, 10, 5);
        LocalDate date2 = LocalDate.of(2026, 12, 10);

        Period period = Period.between(date1, date2);
        System.out.println("Period between dates: " + period);
    }
}

Output
Period between dates: P3Y2M5D

7. Normalizing a Period

public class PeriodExample {
    public static void main(String[] args) {
        Period period = Period.of(1, 13, 35);
        Period normalizedPeriod = period.normalized();
        System.out.println("Normalized Period: " + normalizedPeriod);
    }
}

output
Normalized Period: P1Y1M5D

TemporalAdjusters, TemporalUnit, TemporalAmount

TemporalAdjusters TemporalAdjusters is a utility class that provides a set of predefined adjusters for manipulating date-time objects. These adjusters can be used to adjust a date to the first day of the month, the last day of the month, the next Tuesday, and so on.

TemporalUnit

TemporalUnit is an interface that represents a unit of date-time measurement, such as days, months, or years. It is used to perform arithmetic on date-time objects.

TemporalAmount

TemporalAmount is an interface that represents an amount of time, such as a period of days or a duration of hours. It is used to add or subtract amounts of time from date-time objects.

Here are some common examples of using TemporalAdjusters, TemporalUnit, and TemporalAmount, along with their expected outputs:

1. Using TemporalAdjusters

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;

public class TemporalAdjustersExample {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2023, 10, 5);

        // Adjust to the first day of the month
        LocalDate firstDayOfMonth = date.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println("First Day of Month: " + firstDayOfMonth);

        // Adjust to the last day of the month
        LocalDate lastDayOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("Last Day of Month: " + lastDayOfMonth);

        // Adjust to the next Tuesday
        LocalDate nextTuesday = date.with(TemporalAdjusters.next(java.time.DayOfWeek.TUESDAY));
        System.out.println("Next Tuesday: " + nextTuesday);

        // Adjust to the first day of the next month
        LocalDate firstDayOfNextMonth = date.with(TemporalAdjusters.firstDayOfNextMonth());
        System.out.println("First Day of Next Month: " + firstDayOfNextMonth);
    }
}

output
First Day of Month: 2023-10-01
Last Day of Month: 2023-10-31
Next Tuesday: 2023-10-10
First Day of Next Month: 2023-11-01

2. Using TemporalUnit

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class TemporalUnitExample {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2023, 10, 5);

        // Adding 5 days
        LocalDate newDate = date.plus(5, ChronoUnit.DAYS);
        System.out.println("Date after adding 5 days: " + newDate);

        // Subtracting 2 months
        newDate = date.minus(2, ChronoUnit.MONTHS);
        System.out.println("Date after subtracting 2 months: " + newDate);

        // Calculating the difference between dates in days
        LocalDate anotherDate = LocalDate.of(2023, 10, 10);
        long daysBetween = ChronoUnit.DAYS.between(date, anotherDate);
        System.out.println("Days between dates: " + daysBetween);
    }
}

output
Date after adding 5 days: 2023-10-10
Date after subtracting 2 months: 2023-08-05
Days between dates: 5

3. Using TemporalAmount

import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.TemporalAmount;

public class TemporalAmountExample {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2023, 10, 5);

        // Creating a period of 3 years, 2 months, and 5 days
        TemporalAmount period = Period.of(3, 2, 5);

        // Adding the period to the date
        LocalDate newDate = date.plus(period);
        System.out.println("Date after adding period: " + newDate);

        // Subtracting the period from the date
        newDate = date.minus(period);
        System.out.println("Date after subtracting period: " + newDate);
    }
}

output
Date after adding period: 2026-12-10
Date after subtracting period: 2020-07-30

4. Combining TemporalAdjusters and TemporalAmount

import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.TemporalAmount;

public class CombinedExample {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2023, 10, 5);

        // Creating a period of 1 year and 1 month
        TemporalAmount period = Period.of(1, 1, 0);

        // Adjusting to the first day of the next month and then adding the period
        LocalDate adjustedDate = date.with(TemporalAdjusters.firstDayOfNextMonth()).plus(period);
        System.out.println("Adjusted Date: " + adjustedDate);
    }
}

Output
Adjusted Date: 2024-12-01

5. Custom TemporalAdjuster

import java.time.LocalDate;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;

public class CustomTemporalAdjusterExample {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2023, 10, 5);

        // Custom adjuster to adjust to the 15th day of the month
        TemporalAdjuster adjuster = temporal -> {
            if (temporal.isSupported(ChronoUnit.DAYS)) {
                temporal = temporal.with(ChronoUnit.DAY_OF_MONTH.getDuration().getAmount(), 15);
            }
            return temporal;
        };

        LocalDate adjustedDate = date.with(adjuster);
        System.out.println("Adjusted Date: " + adjustedDate);
    }
}

output
Adjusted Date: 2023-10-15

👏 If you found my articles useful, please consider giving it claps and sharing it with your friends and colleagues.

To read other topics

👏 If you found my articles useful, please consider giving it claps and sharing it with your friends and colleagues.

To read other topics


메타데이터
post_id
de97d6e5b14d
slug
understanding-javas-date-and-time-api-a-detailed-exploration-of-java-time-de97d6e5b14d
url
https://medium.com/@vino7tech/understanding-javas-date-and-time-api-a-detailed-exploration-of-java-time-de97d6e5b14d
canonical_url
https://medium.com/@vino7tech/understanding-javas-date-and-time-api-a-detailed-exploration-of-java-time-de97d6e5b14d
author_url
https://medium.com/@vino7tech
status
ok
fetched_at
2026-07-22 18:10:51