Java Get Last Date of Current Week
In this Java tutorial, we learn how to get the last day of current week as a Date object in Java programming language.
How to get last Date of current week in Java
At this first step, we create a new Java class named DateUtil, and implement a new static method named getLastDateOfCurrentWeek(), in this method we populate to get the last day Sunday 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 get the last Date of current week.
* @return Sunday Date of current week.
*/
public static Date getLastDateOfCurrentWeek() {
Calendar calendar = Calendar.getInstance();
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if(dayOfWeek != Calendar.SUNDAY) {
calendar.add(Calendar.DATE, (8 - dayOfWeek));
}
return calendar.getTime();
}
}
In the following example Java code, we learn how to use the above static method to get the last day of current week as a Date object in Java program.
GetLastDateOfCurrentWeekExample.java
import java.util.Date;
public class GetLastDateOfCurrentWeekExample {
public static void main(String... args) {
// Get Last Date of Current Week
Date firstDateOfWeek = DateUtil.getLastDateOfCurrentWeek();
System.out.println("Today: " + new Date());
System.out.println("Last day of current week: " + firstDateOfWeek);
}
}
Today: Sat Aug 20 00:52:47 ICT 2022
Last day of current week: Sun Aug 21 00:52:47 ICT 2022
Happy Coding 😊
Related Articles
Java Get First 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