Get next Sunday
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] argv) {
System.out.println(getSunday(new Date()));
}
public static Date getSunday(Date today) {
Calendar cal = Calendar.getInstance();
cal.setTime(today);
int dow = cal.get(Calendar.DAY_OF_WEEK);
while (dow != Calendar.SUNDAY) {
int date = cal.get(Calendar.DATE);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
if (date == getMonthLastDate(month, year)) {
if (month == Calendar.DECEMBER) {
month = Calendar.JANUARY;
cal.set(Calendar.YEAR, year + 1);
} else {
month++;
}
cal.set(Calendar.MONTH, month);
date = 1;
} else {
date++;
}
cal.set(Calendar.DATE, date);
dow = cal.get(Calendar.DAY_OF_WEEK);
}
return cal.getTime();
}
private static int getMonthLastDate(int month, int year) {
switch (month) {
case Calendar.JANUARY:
case Calendar.MARCH:
case Calendar.MAY:
case Calendar.JULY:
case Calendar.AUGUST:
case Calendar.OCTOBER:
case Calendar.DECEMBER:
return 31;
case Calendar.APRIL:
case Calendar.JUNE:
case Calendar.SEPTEMBER:
case Calendar.NOVEMBER:
return 30;
default: // Calendar.FEBRUARY
return year % 4 == 0 ? 29 : 28;
}
}
}
Home
Java Book
Runnable examples
Java Book
Runnable examples
Date Get:
- Day of Week
- Number of days in a month
- Month of year
- Current month name
- Full date time
- Get all attributes from a Calendar
- Get year, month, day, minute, hour, second, milli second from java.util.Date through Calendar
- Get age from a birthday date
- Get Monday
- Get next Sunday
- Get today's date
- Get the last day of a month
- Get date of yesterday
- Get Day-of-Week for a Particular Date
- Get date of last week
- Get date of last month
- Get last Date of This Month
- Get Month in a leap year
- Get start of a month
- Get the end of a month
- Get noon of a day
- Get days since a date
- Get TimeZone
- Get Last day fo previous Month
- Is an hour between an interval
- Is a Year a Leap Year