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
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.