Java Get First Date of Current Week
In this Java tutorial, we learn how to get the first day of current week as a Date object in Java programming language.
How to get first Date of current week in Java
Firstly, we create a new Java class named DateUtil, and implement the method named getFirstDateOfCurrentWeek(), in this method we populate to get the Monday day of current week and return it as a Date object as the following Java code.
DateUtil.java
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
/**
* This method to return the first Date of current week.
* @return Monday Date object of current week.
*/
public static Date getFirstDateOfCurrentWeek() {
Calendar calendar = Calendar.getInstance();
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if(dayOfWeek == Calendar.SUNDAY) {
calendar.add(Calendar.DATE, -6);
} else {
calendar.add(Calendar.DATE, -dayOfWeek + 2);
}
return calendar.getTime();
}
}
In the following example Java code, we learn how to use the above DateUtil class to get Monday day of current week as a Date object in Java program.
GetFirstDateOfCurrentWeekExample.java
import java.util.Date;
public class GetFirstDateOfCurrentWeekExample {
public static void main(String... args) {
// Get First Date of Current Week
Date firstDateOfWeek = DateUtil.getFirstDateOfCurrentWeek();
System.out.println("Today: " + new Date());
System.out.println("First day of current week: " + firstDateOfWeek);
}
}
Today: Sat Aug 20 00:35:25 ICT 2022
First day of current week: Mon Aug 15 00:35:25 ICT 2022
Happy Coding 😊
Related Articles
Java Get Last Date of Current Week
Java Get First LocalDate of Current Week
Java Get Last LocalDate of Current Week
Java Get First LocalDate of Current Month
Java Get Last LocalDate of Current Month
Java Get First LocalDate of Current Year
Java Get Last LocalDate of Current Year
Java Get First Day of Month from Specified Date
Java Get Last Date of Current Year
Java Get Last Date of Specified Month
Java Get Last Date of Specified Year
Java Get First Date of Current Year