如何从今天起最后两个星期五的日期?

时间:2015-03-05 10:22:00

标签: java

我需要使用今天的日期来获取最后两个星期五的日期。这是我目前正在使用的代码     公共课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));

    }


}

有没有办法优化这段代码?

4 个答案:

答案 0 :(得分:3)

使用Java 8,如果您没有 使用Calendar api,则可以使用TemporalAdjuster

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

注意:需要以下静态导入
import static java.time.temporal.TemporalAdjusters.previous;
import static java.time.DayOfWeek.FRIDAY;

答案 1 :(得分:2)

你可以通过这种方式获得上周五:

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

通过减去一周并将星期设置为星期五来获得上周五。

答案 2 :(得分:1)

尝试类似:

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();

答案 3 :(得分:0)

这一行应该有所帮助:

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

所以这段代码解决了你的问题:

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()));