To get the coming Sunday from the current date or specified date, write the following code:
public static Date getNearestWeekend(Date date)
{
try {
Calendar c = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
// Here you will set cpecified date if provided
if(date != null)
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
// Her we will set cureent date
cal1.setTime(getCurrentDate());
//here we will check if the sunday has passed or not, if yes then will add 7 that will give coming Sunday
if(c.get(Calendar.DAY_OF_MONTH) < cal1.get(Calendar.DAY_OF_MONTH))
c.add(Calendar.DATE,7);
//This will print the coming Sunday date if Sunday has passes otherwise it will print current Sunday
System.out.println("Date: "+c.getTime());
return c.getTime();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
0 Comment(s)