在 java / Quartz 中处理日期的更简洁方式

Cleaner way of dealing with dates in java / Quartz

为了以编程方式提前一天安排工作(使用石英),我不得不想出这些乱七八糟的代码:

Date.from(LocalDateTime.from(Instant.now()).plusDays(1).toInstant(ZoneOffset.ofHours(-3)))

有没有办法让这段可怕的代码更清晰、更易读?

我的目标是简单地选择这一时刻并增加一天,而不用担心时区或某些给定天数的持续时间差异很小。

编辑

更具体地说,我需要一个 java.util.Date 表示比创建时多一天。

有两种形式,据我所知没有偏好。这一个:

    Date sameTimeTomorrow = Date.from(Instant.now().plus(Duration.ofDays(1)));

或者这样:

    Date sameTimeTomorrow = Date.from(Instant.now().plus(1, ChronoUnit.DAYS));

但是请注意,这会在不考虑夏令时或其他异常情况的情况下增加 24 小时。例如:在我的时区,夏令时在 10 月 27 日到 28 日之间的晚上结束。因此,如果我在 10 月 27 日中午 12 点 运行 以上,我将在我的时区中到达 10 月 28 日 13 点,因为时间已经变了。如果我需要再次打到中午12点,我需要:

    Date sameTimeTomorrow = Date.from(
            ZonedDateTime.now(ZoneId.of("America/Sao_Paulo")).plusDays(1).toInstant());

请替换为您的正确时区。

您选择的标题一般要求 Java 日期,但您的问题和标签表明您可能对某些 Quartz-specific 解决方案感兴趣,例如这些(假设您重新使用 TriggerBuilder):

TriggerBuilder tb = ...; // initialize your tb

// Option 1
Trigger trigger = tb
        .withSchedule(/* pick your flavor */)
        .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.DAY))
        .build();

// Option 2
LocalDateTime now = LocalDateTime.now();
Trigger trigger2 = tb
        .withSchedule(/* pick your flavor */)
        .startAt(DateBuilder.tomorrowAt(now.getHour(), now.getMinute(), now.getSecond()))
        .build();

有关详细信息,请查看 DateBuilder API