How do I use java.time.ZoneId class?

java.time.ZoneId is a class in Java’s Date-Time API used to represent a time zone identifier. This identifier is used to get a ZoneRules, which then can be used to convert between an Instant and a LocalDateTime.

Here is how you can use the ZoneId class in a simple way:

package org.kodejava.datetime;

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

public class ZoneIdExample {
    public static void main(String[] args) {
        // Get the system default ZoneId
        ZoneId defaultZoneId = ZoneId.systemDefault();
        System.out.println("System Default TimeZone : " + defaultZoneId);

        // Get ZoneId instance using the specified zone ID as a string
        ZoneId londonZoneId = ZoneId.of("Europe/London");
        System.out.println("London ZoneId : " + londonZoneId);

        // Get ZonedDateTime using ZoneId
        ZonedDateTime zonedDateTimeInLondon = ZonedDateTime.now(londonZoneId);
        System.out.println("Current date and time in London: " + zonedDateTimeInLondon);
    }
}

Output:

System Default TimeZone : Asia/Makassar
London ZoneId : Europe/London
Current date and time in London: 2024-01-19T06:43:23.076855Z[Europe/London]

In the above code:

  • ZoneId.systemDefault() is used to get the system default ZoneId.
  • ZoneId.of(String zoneId) is used to get a ZoneId instance using the specified zone ID as a string. You can get all available zone IDs by calling ZoneId.getAvailableZoneIds().
  • ZonedDateTime.now(ZoneId zoneId) is used to get the current date and time in the specified time zone.

Please note that the ZoneId is immutable and thread-safe, it ensures the class can be used safely in multithreaded systems.

How do I use java.time.Instant class of Java Date-Time API?

The java.time.Instant class in the Java Date-Time API is an immutable representation of a point in time. It stores a long count of seconds from the epoch of the first moment of 1970 UTC, plus a number of nanoseconds for the further precision within that second.

The java.time.LocalDate class represents a date without a time or time zone. It is used to represent just a date as year-month-day (e.g., 2023-03-27) in the ISO-8601 calendar system.

The java.time.LocalTime class represents a time without a date or time zone. It is used to represent just a time as hour-minute-second (e.g., 13:45:20).

It’s also worth noting that Instant class is part of Java 8’s new date and time API which was brought in to address the shortcomings of the old java.util.Date and java.util.Calendar API.

Here’s a quick example of how to use the Instant class:

package org.kodejava.datetime;

import java.time.Instant;

public class InstantExample {
    public static void main(String[] args) {
        // Get the current point in time
        Instant now = Instant.now();
        System.out.println("Current time: " + now);

        // Add duration of 500 seconds from now
        Instant later = now.plusSeconds(500);
        System.out.println("500 seconds later: " + later);

        // Subtract duration of 500 seconds from now
        Instant earlier = now.minusSeconds(500);
        System.out.println("500 seconds earlier: " + earlier);

        // Compare two Instants
        int comparison = now.compareTo(later);
        if (comparison < 0) {
            System.out.println("Now is earlier than later");
        } else if (comparison > 0) {
            System.out.println("Now is later than later");
        } else {
            System.out.println("Now and later are at the same time");
        }
    }
}

Output:

Current time: 2024-01-18T09:26:56.152268Z
500 seconds later: 2024-01-18T09:35:16.152268Z
500 seconds earlier: 2024-01-18T09:18:36.152268Z
Now is earlier than later

In this example, Instant.now() is used to get the current Instant. Various methods like plusSeconds(), minusSeconds(), and compareTo() are used to manipulate and compare the Instant.

LocalDate and LocalTime are local in the sense that they represent date and time from the context of the observer, without a time zone.

To connect Instant with LocalDate and LocalTime, you need a time zone. This is because Instant is in UTC and LocalDate/LocalTime are in a local time zone, so you need to explicitly provide a conversion between them.

Here’s how you convert an Instant to a LocalDate and a LocalTime:

package org.kodejava.datetime;

import java.time.*;

public class InstantConvertExample {
    public static void main(String[] args) {
        Instant now = Instant.now();
        System.out.println("Instant: " + now);

        // Get the system default timezone
        ZoneId zoneId = ZoneId.systemDefault(); 

        LocalDate localDate = now.atZone(zoneId).toLocalDate();
        System.out.println("LocalDate: " + localDate);

        LocalTime localTime = now.atZone(zoneId).toLocalTime();
        System.out.println("LocalTime: " + localTime);
    }
}

Here Instant.now() gives the current timestamp. .atZone(ZoneId.systemDefault()) converts it to ZonedDateTime which is then converted to LocalDate and LocalTime by using .toLocalDate() and .toLocalTime() respectively.

You can also go from LocalDate and LocalTime back to Instant. Here’s how:

package org.kodejava.datetime;

import java.time.*;

public class ToInstantExample {
    public static void main(String[] args) {
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        ZoneId zoneId = ZoneId.systemDefault();
        Instant instantFromDateAndTime = LocalDateTime.of(localDate, localTime).atZone(zoneId).toInstant();

        System.out.println("Instant from LocalDate and LocalTime: " + instantFromDateAndTime);
    }
}

How do I use next() and nextOrSame() method of TemporalAdjusters?

TemporalAdjusters.next(DayOfWeek) and TemporalAdjusters.nextOrSame(DayOfWeek) are part of java.time.temporal.TemporalAdjusters class in Java. They adjust the date to the next, or the first occurrence of the specified DayOfWeek, or stay at the same date if it’s the desired DayOfWeek.

Here is how to use these methods:

package org.kodejava.datetime;

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

public class NextOrSameExample {
    public static void main(String[] args) {
        // Get the current date
        LocalDate date = LocalDate.now();
        System.out.println("Current date: " + date);

        LocalDate nextMonday = date.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
        System.out.println("Next Monday: " + nextMonday);

        LocalDate nextOrSameFriday = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY));
        System.out.println("Next Friday or same day if it's Friday: " + nextOrSameFriday);
    }
}

Output:

Current date: 2024-01-18
Next Monday: 2024-01-22
Next Friday or same day if it's Friday: 2024-01-19

In the above example:

  • LocalDate.now() is used to get the current date.
  • .with(TemporalAdjusters.next(DayOfWeek.MONDAY)) adjusts the date to the next Monday.
  • .with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY)) adjusts the date to the next Friday or stays at the same date if it’s already Friday.

How do I use firstInMonth() and lastInMonth() method of TemporalAdjusters class?

TemporalAdjusters.firstInMonth(DayOfWeek) and TemporalAdjusters.lastInMonth(DayOfWeek) methods are part of the java.time.temporal.TemporalAdjusters class. They adjust the date to the first or last occurrence of the specified DayOfWeek in the month.

Here’s an example of how to use these methods:

package org.kodejava.datetime;

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

public class FirstLastInMonthExample {
    public static void main(String[] args) {
        // Get the current date
        LocalDate date = LocalDate.now();
        System.out.println("Current date: " + date);

        LocalDate firstMondayInMonth = date.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
        System.out.println("First Monday of this month: " + firstMondayInMonth);

        LocalDate lastFridayInMonth = date.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY));
        System.out.println("Last Friday of this month: " + lastFridayInMonth);
    }
}

The output of the code snippet above:

Current date: 2024-01-18
First Monday of this month: 2024-01-01
Last Friday of this month: 2024-01-26

In this example:

  • LocalDate.now()` is used to get the current date.
  • .with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)) adjusts the date to the first Monday of the current month.
  • .with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY)) adjusts the date to the last Friday of the current month.

How do I use firstDayOfYear() and firstDayOfNextYear() method of TemporalAdjusters class?

The TemporalAdjusters.firstDayOfYear() and TemporalAdjusters.firstDayOfNextYear() methods in Java are utilized to adjust a date to the first day of the current year and the first day of the next year respectively.

Here’s how to use these methods:

package org.kodejava.datetime;

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

public class FirstDayOfYearExample {
    public static void main(String[] args) {
        // Det the current date
        LocalDate date = LocalDate.now();
        System.out.println("Current date: " + date);

        LocalDate firstDayOfYear = date.with(TemporalAdjusters.firstDayOfYear());
        System.out.println("First day of this year: " + firstDayOfYear);

        LocalDate firstDayOfNextYear = date.with(TemporalAdjusters.firstDayOfNextYear());
        System.out.println("First day of next year: " + firstDayOfNextYear);
    }
}

In this example:

  • LocalDate.now() is used to get the current date.
  • .with(TemporalAdjusters.firstDayOfYear()) adjusts the date to the first day of the current year.
  • .with(TemporalAdjusters.firstDayOfNextYear()) adjusts the date to the first day of the next year.

The output of the code snippet above:

Current date: 2024-01-18
First day of this year: 2024-01-01
First day of next year: 2025-01-01

How do I use TemporalAdjusters firstDayOfNextMonth() method?

The TemporalAdjusters.firstDayOfNextMonth() method is a useful method in java.time.temporal.TemporalAdjusters class in Java that adjusts the date to the first day of the next month.

Here’s an example usage:

package org.kodejava.datetime;

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

public class FirstDayOfNextMonthExample {
    public static void main(String[] args) {
        // Get the current date
        LocalDate date = LocalDate.now();

        // Adjust to the first day of next month
        LocalDate firstDayOfNextMonth = date.with(TemporalAdjusters.firstDayOfNextMonth());

        System.out.println("Current date: " + date);
        System.out.println("First day of next month: " + firstDayOfNextMonth);
    }
}

Output:

Current date: 2024-01-18
First day of next month: 2024-02-01

In this example, LocalDate.now() is used to get the current date. Then .with(TemporalAdjusters.firstDayOfNextMonth()) is used to adjust the date to the first day of the next month.

How do I use TemporalAdjusters firstDayOfMonth() method?

The TemporalAdjusters.firstDayOfMonth() method in Java is used to obtain a copy of the current date with the day set to the first day of the current month.

This method is quite simple to use. You need to import the java.time package and use the with() function in conjunction with TemporalAdjusters.firstDayOfMonth().

Here’s a simple example in Java:

package org.kodejava.datetime;

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

public class FirstDayOfMonthExample {
    public static void main(String[] args) {
        // Get the current date
        LocalDate date = LocalDate.now();

        // Adjust to first day of current month
        LocalDate firstDayOfMonth = date.with(TemporalAdjusters.firstDayOfMonth());

        System.out.println("Current date: " + date);
        System.out.println("First day of this month: " + firstDayOfMonth);
    }
}

Output:

Current date: 2024-01-18
First day of this month: 2024-01-01

In this example, LocalDate.now() is used to get the current date. Then .with(TemporalAdjusters.firstDayOfMonth()) is used to adjust the date to the first day of the current month.

How do I use TemporalAdjusters dayOfWeekInMonth() method?

dayOfWeekInMonth() is a handy method in java.time.temporal.TemporalAdjusters class that returns an adjuster which changes the date to the n-th day of week in the current month.

Here is an example of how you could use it:

package org.kodejava.datetime;

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

public class DayOfWeekInMonthExample {
    public static void main(String[] args) {
        // Current date
        LocalDate date = LocalDate.now();

        // The 2nd Tuesday in the month of the date.
        LocalDate secondTuesday = date.with(
                TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.TUESDAY));

        System.out.println("Current Date: " + date);
        System.out.println("Second Tuesday: " + secondTuesday);
    }
}

Output:

Current Date: 2024-01-18
Second Tuesday: 2024-01-09

This code would display the date of the second Tuesday in the current month.

Here’s what’s going on in this case:

  • TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.TUESDAY) specifies that we want the second occurrence of DayOfWeek.TUESDAY in the current month.

  • date.with(TemporalAdjuster) modifies the LocalDate date based on the TemporalAdjuster that is passed in. The original date object is unchanged; a new LocalDate reflecting the adjusted date is returned.

This TemporalAdjusters method is very useful when you have conditional logic based on things like “if it’s the third Monday of the month, then…”

How do I use java.time.temporal.TemporalAdjusters class?

The java.time.temporal.TemporalAdjuster interface and the java.time.temporal.TemporalAdjusters class are both part of the Java Date-Time API, and they work together for adjusting temporal objects.

TemporalAdjuster interface:

This is a functional interface, which means it has only one abstract method, adjustInto(). This method is meant to adjust a temporal object, such as LocalDate, LocalDateTime, YearMonth, etc. The single method makes it a suitable target for lambdas, which makes creating custom temporal adjusters a lot easier.

TemporalAdjusters class:

This class is effectively a factory/utility class that provides a number of pre-built implementations of TemporalAdjuster that are commonly useful. These include adjusters to find the first/last day of the month, the next/previous day of the week, the next/previous occurrence of a specific day of the week and so on.

For example, if you wanted to find the next Friday, you would use TemporalAdjusters to provide an implementation of TemporalAdjuster:

LocalDate nextFriday = LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.FRIDAY));

In this code, TemporalAdjusters.next(DayOfWeek.FRIDAY) is an instance of TemporalAdjuster interface. The next() static method in TemporalAdjusters class provides the instance of TemporalAdjuster.

Thus, while TemporalAdjuster provides the mechanism to adjust temporal objects, TemporalAdjusters provide a handy collection of frequently used implementations of this mechanism.

Let’s dive into how they’re commonly utilized:

1. Use predefined TemporalAdjusters

The TemporalAdjusters class provides several static methods that return commonly used adjusters. For example, to get the next Sunday:

LocalDate localDate = LocalDate.now();
LocalDate nextSunday = localDate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));

Or the last day of the month:

LocalDate lastDayOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth());

2. Custom TemporalAdjuster

You can also create your own custom TemporalAdjuster. For example, let’s suppose we want a TemporalAdjuster that sets the time to 9 a.m.:

TemporalAdjuster adjuster = temporal -> {
    return temporal.with(ChronoField.HOUR_OF_DAY, 9)
        .with(ChronoField.MINUTE_OF_HOUR, 0)
        .with(ChronoField.SECOND_OF_MINUTE, 0)
        .with(ChronoField.NANO_OF_SECOND, 0);
};

LocalDateTime ldt = LocalDateTime.now();
ldt = ldt.with(adjuster);

In this case, ldt is a new LocalDateTime that shares the date with the original LocalDateTime, but the time is set to 9 a.m.

3. Using TemporalAdjuster in date calculations

TemporalAdjuster can also be used in more advanced date calculations such as finding the next weekday:

TemporalAdjuster NEXT_WORKDAY = TemporalAdjusters.ofDateAdjuster(
    date -> {
        DayOfWeek dow = date.getDayOfWeek();
        int daysToAdd = 1;
        if (dow == DayOfWeek.FRIDAY)
            daysToAdd = 3;
        else if (dow == DayOfWeek.SATURDAY)
            daysToAdd = 2;
        return date.plusDays(daysToAdd);
    });
LocalDate nextWorkDay = localDate.with(NEXT_WORKDAY);

In this code block, NEXT_WORKDAY is a TemporalAdjuster that adjusts the date to the next workday. If the date falls on a Friday, it adds three days to skip the weekend. If it falls on a Saturday, it adds two days. In all other cases, it adds one day.

The java.time.temporal.TemporalAdjusters class comes with many predefined TemporalAdjuster implementations that are useful for common tasks. Here are some of them:

Temporal Adjuster Description
dayOfWeekInMonth(int ord, DayOfWeek dow) Returns a new date in the same month with the ordinal day-of-week. The ordinal parameter allows you to specify which day of the week in the month, such as the “second Tuesday”.
firstDayOfMonth() Returns a new date set to the first day of the current month.
firstDayOfNextMonth() Returns a new date set to the first day of the next month.
firstDayOfNextYear() Returns a new date set to the first day of the next year.
firstDayOfYear() Returns a new date set to the first day of the current year.
firstInMonth(DayOfWeek dow) Returns a new date in the same month with the first matching day-of-week. For example, “first Wednesday in March”.
lastDayOfMonth() Returns a new date set to the last day of the current month.
lastDayOfYear() Returns a new date set to the last day of the current year.
lastInMonth(DayOfWeek dow) Returns a new date in the same month with the last matching day-of-week. For example, “last Wednesday in March”.
next(DayOfWeek dow) or nextOrSame(DayOfWeek dow) Returns a new date that falls on the next specified day-of-week. If the current day is the specified day, this method returns a new date that is a week later. The nextOrSame() method will return today’s date if today is the specified day.
previous(DayOfWeek dow) or previousOrSame(DayOfWeek dow) Behaves like next() or nextOrSame(), but returns a date that falls on the previous specified day-of-week.

These methods can all be used with the with() method of a date-based temporal object. For example:

// To get the last day of the current month:
LocalDate endOfMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());

How do I use java.time.Duration class?

java.time.Duration is another useful class in Java for dealing with time. It measures time in seconds and nanoseconds and is most suitable for smaller amounts of time, like “20 seconds” or “3 hours”, and not for larger units like “3 days” or “4 months”. Here’s a guide on how to use it:

1. Creating a Duration instance

You can create an instance of Duration using one of its static factory methods that best suits your needs, such as ofSeconds(), ofMinutes(), ofHours(), or ofMillis().

//create a duration of 60 seconds
Duration duration = Duration.ofSeconds(60);

//create a duration of 2 hours
Duration twoHours = Duration.ofHours(2);

2. Creating a Duration between two Instants

Duration also provides a static method between() that can be used to find the duration between two points in time.

Instant start = Instant.now();
// Do some time consuming task...
Instant end = Instant.now();

Duration duration = Duration.between(start, end);

3. Retrieving the Duration

You can retrieve the number of days, hours, minutes, or seconds in a Duration using methods like toDays(), toHours(), toMinutes(), or getSeconds().

long hours = twoHours.toHours();  // returns 2

4. Adding and Subtracting from a Duration

Duration can be added or subtracted from another using the plus() and minus() methods or the more specific plus / minus methods such as plusHours(), minusMinutes(), etc.

// Adding
Duration additionalDuration = duration.plusHours(4);

// Subtracting
Duration lessDuration = additionalDuration.minusMinutes(50);

5. Comparing Durations

The Duration class provides compareTo(), equals(), negated(), and abs() methods for comparison:

Duration duration1 = Duration.ofHours(4);
Duration duration2 = Duration.ofHours(2);

// Returns a negative number, zero, or positive number if less than, 
// equal to, or greater than the other.
int comparison = duration1.compareTo(duration2);

boolean equals = duration1.equals(duration2); // false

// Returns a duration with the new duration being negative of this 
// duration.
Duration negated = duration1.negated(); 

// Returns a duration with the new duration being absolute of 
// this duration, effectively, it returns the same as duration1.
Duration abs = negated.abs();