简体   繁体   中英

how to get date of last two Fridays from today?

I need to get the dates of last two Fridays using today's date.This is the code I'm currently using public class GetDate {

public static void main(String[] args) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date dt = new Date();
    Calendar c = Calendar.getInstance();
    c.setTime(dt);
    System.out.println("today : " + sdf.format(dt));
    while (c.get(Calendar.DAY_OF_WEEK) != 6) {
        c.add(Calendar.DATE, -1);
    }
    Date lastFri=c.getTime();
    System.out.println("last fri : "+sdf.format(lastFri));
    c.add(Calendar.DATE, -7);
    Date prevFri = c.getTime();
    System.out.println("previous friday : "+sdf.format(prevFri));

    }


}

Is there any way to optimize this code??

With Java 8, and if you don't have to use the Calendar api, you can use a TemporalAdjuster :

LocalDate today = LocalDate.now();
LocalDate prevFriday = today.with(previous(FRIDAY));
LocalDate prevPrevFriday = prevFriday.with(previous(FRIDAY));

note: requires the following static import
import static java.time.temporal.TemporalAdjusters.previous;
import static java.time.DayOfWeek.FRIDAY;

You could get the last Friday this way :

Calendar cal = Calendar.getInstance();
cal.add(Calendar.WEEK_OF_YEAR, -1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);

This gets the last Friday by subtracting a week and setting the day of week to Friday.

Try something like:

cal.add(Calendar.WEEK_OF_YEAR, -1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
Date lastFriday = cal.getTime();
cal.add(Calendar.WEEK_OF_YEAR, -1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
Date lastToLastFriday = cal.getTime();

This line should help:

calendar.add(Calendar.DATE, Calendar.FRIDAY - 7 - c.get(Calendar.DAY_OF_WEEK));

So this code is solving your problem:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = GregorianCalendar.getInstance();
c.add(Calendar.DATE, Calendar.FRIDAY - 7 - c.get(Calendar.DAY_OF_WEEK));
System.out.println(sdf.formate(c.getTime()));
c.add(Calendar.DATE, Calendar.FRIDAY - 14 - c.get(Calendar.DAY_OF_WEEK));
System.out.println(sdf.formate(c.getTime()));

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