有没有一个好方法可以得到即将到来的星期三的日期?tl;博士详

2022-09-03 16:29:59

有没有一个好方法可以得到即将到来的星期三的日期?也就是说,如果今天是星期二,我想得到本周星期三的日期;如果今天是星期三,我想得到下个星期三的日期;如果今天是星期四,我想在下周得到星期三的日期。

谢谢。


答案 1

基本算法如下:

  • 获取当前日期
  • 获取星期几
  • 找出它与星期三的不同之处
  • 如果差异不为正数,则添加 7(即坚持下一个来临/将来的日期)
  • 添加差异

下面是一个代码片段,演示如何执行此操作:java.util.Calendar

import java.util.Calendar;

public class NextWednesday {
    public static Calendar nextDayOfWeek(int dow) {
        Calendar date = Calendar.getInstance();
        int diff = dow - date.get(Calendar.DAY_OF_WEEK);
        if (diff <= 0) {
            diff += 7;
        }
        date.add(Calendar.DAY_OF_MONTH, diff);
        return date;
    }
    public static void main(String[] args) {
        System.out.printf(
            "%ta, %<tb %<te, %<tY",
            nextDayOfWeek(Calendar.WEDNESDAY)
        );
    }
}

相对于我现在的此时此地,上述片段的输出是 ."Wed, Aug 18, 2010"

接口链接


答案 2

tl;博士

LocalDate                        // Represent a date-only value, without time-of-day and without time zone.
.now()                           // Capture the current date as seen in the wall-clock time used by the people of a specific region (a time zone). The JVM’s current default time zone is used here. Better to specify explicitly your desired/expected time zone by passing a `ZoneId` argument. Returns a `LocalDate` object.
.with(                           // Generate a new `LocalDate` object based on values of the original but with some adjustment. 
    TemporalAdjusters            // A class that provides some handy pre-defined implementations of `TemporalAdjuster` (note the singular) interface.
    .next(                       // An implementation of `TemporalAdjuster` that jumps to another date on the specified day-of-week.
        DayOfWeek.WEDNESDAY      // Pass one of the seven predefined enum objects, Monday-Sunday.
    )                            // Returns an object implementing `TemporalAdjuster` interface.
)                                // Returns a `LocalDate` object.

使用Java8日期时间API,您可以轻松找到即将到来的星期三。

LocalDate nextWed = LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));

next(DayOfWeek dayOfWeek) - 返回星期二的调整器,该调整器将日期调整为在调整日期后指定星期的第一个匹配项。

假设如果你想得到前一个星期三,那么,

LocalDate prevWed = LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.WEDNESDAY));

previous(DayOfWeek dayOfWeek) - 返回前一个星期的调整器,该调整器将日期调整为在调整日期之前指定的星期几的第一次出现。

假设如果你想得到下一个或当前的星期三,那么

LocalDate nextOrSameWed = LocalDate.now().with(TemporalAdjusters.nextOrSame(DayOfWeek.WEDNESDAY));

nextOrSame(DayOfWeek dayOfWeek) - 返回星期二或同一天的调整器,该调整器将日期调整为在调整日期后指定星期的第一个匹配项,除非它已经在那一天,在这种情况下,将返回相同的对象。

编辑:您还可以传递 ZoneId 以从指定时区的系统时钟获取当前日期。

ZoneId zoneId = ZoneId.of("UTC");
LocalDate nextWed = LocalDate.now(zoneId).with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));

有关更多信息,请参阅时间调整