How Do You Get The First Day Of The Week In Java
Chapter:
Date and Time
Last Updated:
15-09-2023 06:26:25 UTC
Program:
/* ............... START ............... */
// Using java.util.Calendar (prior to Java 8):
import java.util.Calendar;
public class FirstDayOfWeekExample {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
System.out.println("First day of the week: " + calendar.getTime());
}
}
// Using java.time (Java 8 and later):
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class FirstDayOfWeekExample {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
LocalDate firstDayOfWeek = currentDate.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
System.out.println("First day of the week: " + firstDayOfWeek);
}
}
/* ............... END ............... */
Output
Sample Output Using java.util.Calendar (prior to Java 8):
First day of the week: Mon Sep 12 00:00:00 UTC 2023
Sample Output Using java.time (Java 8 and later):
First day of the week: 2023-09-11
Notes:
-
In first code uses Calendar.getInstance() to get the current date and time, and then sets the DAY_OF_WEEK field to the value of getFirstDayOfWeek(), which represents the first day of the week for the default locale.
- In Java 8 and later, the java.time package provides a more modern and easier-to-use API for working with dates and times. In this example, we use LocalDate.now() to get the current date, and then use TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY) to find the first day of the week (assuming Monday as the first day).
- Choose the method that best fits your Java version and coding style.