Reputation: 3186
I want to find the date of the first occurrence of a Sunday before a given date.
e.g. I have a method that excepts current date and lets say the date is today's date Tuesday 02-09-2014 and the method will return the date of the past Sunday 31-08-2014.
Is there any way that I can get it done in Java??
Thanks in advance
Upvotes: 1
Views: 190
Reputation: 5426
Using java.util.Calendar
Substract the difference (in days) between sunday and now:
Calendar c = Calendar.getInstance();
int day = c.get( Calendar.DAY_OF_WEEK );
c.add( Calendar.DAY_OF_WEEK, Calendar.SUNDAY - day);
And you got it.
Upvotes: 0
Reputation: 16641
Something like this will work.
Calendar cal = Calendar.getInstance();
int diff = cal.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY;
cal.add(Calendar.DAY_OF_MONTH, -diff);
System.out.println(cal.getTime());
Upvotes: 0
Reputation: 3682
Try this:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_WEEK, -(cal.get(Calendar.DAY_OF_WEEK) - 1));
System.out.println(cal.getTime());
Upvotes: 0
Reputation: 328598
With java 8 you can use one of the built-in TemporalAdjusters:
LocalDate today = LocalDate.now();
LocalDate previousSunday = today.with(previous(SUNDAY));
//or if today is a Sunday and you want to return today:
LocalDate previousSunday = today.with(previousOrSame(SUNDAY));
note: assumes static imports:
import static java.time.DayOfWeek.SUNDAY;
import static java.time.temporal.TemporalAdjusters.previous;
Upvotes: 1