Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the past Sunday and the coming Sunday in Java? [duplicate]

Tags:

java

date

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 ?

like image 219
Frank Avatar asked Dec 27 '10 01:12

Frank


People also ask

How to get previous Sunday date 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() .

Is LocalDate immutable?

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.


2 Answers

java.time

Briefly:

LocalDate.now().with( next( SUNDAY ) ) 

See this code run live at IdeOne.com.

Details

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;
like image 188
Bobby Eickhoff Avatar answered Sep 27 '22 03:09

Bobby Eickhoff


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.

like image 26
Frank Avatar answered Sep 26 '22 03:09

Frank