How do I get the first Sunday of the year in Java?

The following code snippet help you find the first Sunday of the year, or you can replace it with any day that you want. To achieve this we can use the TemporalAdjusters.firstInMonth adjusters, these adjusters returns a new date in the same month with the first matching day-of-week. This is used for expressions like ‘first Sunday in January’.

Because we want to get the first Sunday of the year first we create a LocalDate which represent the 1st January 2020. Then we call the with() method and pass the firstInMonth adjusters with the DayOfWeek.SUNDAY to find. Beside using Java 8 date time API, you can also use the old java.util.Calendar class as also shown in the code snippet below. But using the new date time API give you a more readable, simpler and less code to write.

package org.kodejava.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.util.Calendar;

import static java.time.temporal.TemporalAdjusters.firstInMonth;

public class FirstSundayOfTheYear {
    public static void main(String[] args) {
        // Get the first Sunday of the year using Java 8 date time
        LocalDate now = LocalDate.of(2020, Month.JANUARY, 1);
        LocalDate sunday = now.with(firstInMonth(DayOfWeek.SUNDAY));
        System.out.println("The first Sunday of 2020 falls on: " + sunday);

        // Get the first Sunday of the year using the old java.util.Calendar
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        calendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.YEAR, 2020);
        System.out.println("The first Sunday of 2020 falls on: " + calendar.getTime());
        System.out.println("The first Sunday of 2020 falls on: " +
                LocalDate.ofInstant(calendar.getTime().toInstant(), ZoneId.systemDefault()));
    }
}

This code snippet will print out the following output:

The first Sunday of 2020 falls on: 2020-01-05
The first Sunday of 2020 falls on: Sun Jan 05 22:43:37 CST 2020
The first Sunday of 2020 falls on: 2020-01-05
Wayan

Leave a Reply

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