时间:如何获得下周五?java.time

2022-08-31 13:36:23

我如何使用Joda-Time API获得下周五。

今天的本地日期是 。在我看来,你必须决定你是在本周的星期五之前还是之后。请参阅此方法:today

private LocalDate calcNextFriday(LocalDate d) {
    LocalDate friday = d.dayOfWeek().setCopy(5);
    if (d.isBefore(friday)) {
        return d.dayOfWeek().setCopy(5);
    } else {
        return d.plusWeeks(1).dayOfWeek().setCopy(5);
    }
}

是否可以缩短或使用单线?

PS:请不要建议我使用JDK日期/时间的东西。Joda-Time是一个更好的API。

Java 8引入了java.time包(Tutorial),它甚至更好。


答案 1

java.time

借助 Java 8 及更高版本中内置的 java.time 框架(教程),您可以使用 TemporalAdjusters 获取周中的下一天或一天

private LocalDate calcNextFriday(LocalDate d) {
  return d.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
}

答案 2

有可能以一种更容易阅读的方式做到这一点:

if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
    return d.withDayOfWeek(DateTimeConstants.FRIDAY));
} else if (d.getDayOfWeek() == DateTimeConstants.FRIDAY) {
    // almost useless branch, could be merged with the one above
    return d;
} else {
    return d.plusWeeks(1).withDayOfWeek(DateTimeConstants.FRIDAY));
}

或以更短的形式

private LocalDate calcNextFriday(LocalDate d) {    
    if (d.getDayOfWeek() < DateTimeConstants.FRIDAY) {
        d = d.withDayOfWeek(DateTimeConstants.FRIDAY));
    } else {
        d = d.plusWeeks(1).withDayOfWeek(DateTimeConstants.FRIDAY));
    }    
    return d; // note that there's a possibility original object is returned
}

甚至更短

private LocalDate calcNextFriday(LocalDate d) {
    if (d.getDayOfWeek() >= DateTimeConstants.FRIDAY) {
        d = d.plusWeeks(1);
    }
    return d.withDayOfWeek(DateTimeConstants.FRIDAY);
}

PS.我没有测试实际的代码!:)