简体   繁体   中英

Getting previous particular day in a week

I am using java date java.util.Calendar and java.text.SimpleDateFormat for my report page.

I want to always set the start date to previous saturday and end date to friday after that saturday.

I wrote a java code which checks this and does it as follows but I am sure its wrong logic wise

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar         cal = Calendar.getInstance();
cal.add(Calendar.DATE, -7);
setToDate(sdf.format(cal.getTime()));
cal.add(Calendar.DATE, -6);
setFromDate(sdf.format(cal.getTime()));

How to get previous FromDate(yyyy-mm-dd) and ToDate(yyyy-mm-dd) where FromDate should be last saturday and ToDate should be last friday.

情况1

案例2

int daysBackToSat = cal.get(Calendar.DAY_OF_WEEK );

cal.add(Calendar.DATE, daysBackToSat*-1);
System.out.println(sdf.format(cal.getTime()));

in line 1 you get a number indicating the current day of the week. which is 1 for sunday ,7 for saturday, 6 for friday, etc. so say if it's Wednesday today you'll get a 4. since saturday is 7 and tehre is no "day 0", you substract 4 days from the current date (line 2). in order to get the next friday after your saturday, you just add 6 days.

EDIT: considering your update i see, that if it's wednesday you don't want to have the saturday before that, but 1 week earlier. if it's already saturday, you'll go back only 1 week. in that case you check, if the "daysBackToSat" is 7, then leave it that way, if it's less than 7 then add another 7 to it.

        if(daysBackToSat<7) {
            daysBackToSat += 7;
        }

I recently developed Lamma Date , which is very good to serve this use case.

    Date today = new Date(2014, 7, 1);

    Date to = today.previous(DayOfWeek.FRIDAY);  // Date(2014,6,27)
    Date from = to.previous(DayOfWeek.SATURDAY); // Date(2014,6,21)

I believe that this question, and the accepted answer, may well have led to a story in TheDailyWTF

As that article rightly states, Java's Date and Calendar types are legacy jokes and best avoided. The right solution is to use Joda Time, or its successor, the java.time framework built into Java 8 and later ( Tutorial ):

date.withDayOfWeek(DateTimeConstants.SATURDAY)

Also... SimpleDateFormat is one of the least thread-safe classes in the entire standard library, and is a disaster waiting to happen!

java.time

This work is much easier and more straight-forward using the java.time framework built into Java 8 and later. Much of the java.time functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP .

See Oracle Tutorial to learn more.

Temporal adjuster

Use a Temporal Adjuster to manipulate a LocalDate into another LocalDate instance. The TemporalAdjusters class (note the plural) offers pre-defined adjusters for your purpose, making use of the handy DayOfWeek enum:

Time zone

Note that time zone is crucial to determining the current date. Your Question ignores this issue. For any given moment the date various around the globe by time zone. For example, a few minutes after midnight in Paris is a new day while still “yesterday” in Montréal.

If omitted, the JVM's current default time zone is applied implicitly. This default can change at any moment during runtime(!) so better to explicitly specify the expected/desired time zone.

ZoneId zoneId = ZoneId.of( "America/Montreal" ) ;
LocalDate localDate = LocalDate.now( zoneId ) ;

Previous Saturday, followed by Friday

Next we get the previous Saturday. Your Question fails to mention what to do if today is Saturday. This code uses previous but your business rules may require previousOrSame , up to you.

LocalDate previousSaturday = localDate.with( TemporalAdjusters.previous( DayOfWeek.SATURDAY ) ) ;

Next requirement is to get the Friday following that previous Saturday. We could add a count of days until Friday, but why bother with the calculation now that we know about temporal adjusters?

LocalDate fridayFollowingPreviousSaturday = previousSaturday.with( TemporalAdjusters.next( DayOfWeek.FRIDAY ) ) ; 

I tried this code and it seems to work:

// Get milliseconds of 1 day
long millisecOneDay = TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS);

// Get actual date
Date today = new Date();

// 0 Sunday, 1 Monday...
int day = today.getDay(); // It use a deprecated method

// Previous saturday
long millisecPrevSat = today.getTime() - (day + 1) * millisecOneDay;

// Previous friday
long millisecNextFri = millisecPrevSat + (6 * millisecOneDay);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

// setToDate(sdf.format(new Date(millisecPrevSat)));
System.out.println("PREV SAT: " + sdf.format(new Date(millisecPrevSat)));

// setFromDate(sdf.format(new Date(millisecNextFri)));
System.out.println("NEXT FRID: " + sdf.format(new Date(millisecNextFri)));

You can check if Friday it's today, and move both dates another 7 days back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM