首页 > 解决方案 > Java 11 时间 - 今天是(长)时间戳

问题描述

我在 mongo 文档字段中保存了一个 cronjob 字符串。我得到下一个有效(长时间)时间

CronExpression exp = new CronExpression(billing.getReminder());
            
long nextReminder = exp.getNextValidTimeAfter(new Date()).getTime();

我的想法是检查这个“nextReminder”是否是今天()然后创建一些任务。使用 java 11 检查它的最佳方法是什么?

标签: javajava-time

解决方案


你可以拿来java.time做个对比...

有一个Instant表示时间的时刻,就像以纪元毫秒为单位的时间戳一样 (⇒ your long nextReminder) 以及现在OffsetDateTime.now()的实际时刻以及仅描述日期部分的部分。LocalDate

您可以使用以下方法确定是否nextReminder今天:

/**
 * <p>
 * Checks if the day (or date) of a given timestamp (in epoch milliseconds)
 * is the same as <em>today</em> (the day this method is executed).<br>
 * <strong>Requires an offset in order to have a common base for comparison</strong>
 * </p>
 *
 * @param epochMillis   the timestamp in epoch milliseconds to be checked
 * @param zoneOffset    the offset to be used as base of the comparison
 * @return <code>true</code> if the dates of the parameter and today are equal,
 *         otherwise <code>false</code>
 */
public static boolean isToday(long epochMillis, ZoneOffset zoneOffset) {
    // extract the date part from the parameter with respect to the given offset
    LocalDate datePassed = Instant.ofEpochMilli(epochMillis)
                                .atOffset(zoneOffset)
                                .toLocalDate();
    // then extract the date part of "now" with respect to the given offset
    LocalDate today = Instant.now()
                                .atOffset(zoneOffset)
                                .toLocalDate();
    // then return the result of an equality check
    return datePassed.equals(today);
}

然后就这样称呼它

boolean isNextReminderToday = isToday(nextReminder, ZoneOffset.systemDefault());

这将使用系统的时间偏移量。也许,ZoneOffset.UTC也可能是一个明智的选择。


推荐阅读