I asked How to detect if a date is within this or next week in Java? but the answers were confusing, so now I think if I can find the past Sunday and the coming Sunday, any day in between is this week, and any day between the coming Sunday and the Sunday after that is next week, am I correct ?
So my new question is : How to get the past Sunday and the coming Sunday in Java ?
If today is Sunday and you would like the result to be today rather than a week ago, call previousOrSame(DayOfWeek dayOfWeek) . LocalDate . now() .
LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day. Other date fields, such as day-of-year, day-of-week and week-of-year, can also be accessed.
Briefly:
LocalDate.now().with( next( SUNDAY ) )
See this code run live at IdeOne.com.
I thought I'd add a Java 8 solution for posterity. Using LocalDate
, DayOfWeek
, and TemporalAdjuster
implementation found in the TemporalAdjusters
class.
final LocalDate today = LocalDate.of(2015, 11, 20);
final LocalDate nextSunday = today.with(next(SUNDAY));
final LocalDate thisPastSunday = today.with(previous(SUNDAY));
This approach also works for other temporal classes like ZonedDateTime
.
import
As written, it assumes the following static imports:
import java.time.LocalDate;
import static java.time.DayOfWeek.SUNDAY;
import static java.time.temporal.TemporalAdjusters.next;
import static java.time.temporal.TemporalAdjusters.previous;
How about this :
Calendar c=Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
c.set(Calendar.HOUR_OF_DAY,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
DateFormat df=new SimpleDateFormat("EEE yyyy/MM/dd HH:mm:ss");
System.out.println(df.format(c.getTime())); // This past Sunday [ May include today ]
c.add(Calendar.DATE,7);
System.out.println(df.format(c.getTime())); // Next Sunday
c.add(Calendar.DATE,7);
System.out.println(df.format(c.getTime())); // Sunday after next
The result :
Sun 2010/12/26 00:00:00
Sun 2011/01/02 00:00:00
Sun 2011/01/09 00:00:00
Any day between the first two is this week, anything between the last two is next week.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With