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
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024