问题描述
我在mongo文档字段中保存了一个cronjob字符串。我得到下一个有效的(长时间)时间
CronExpression exp = new CronExpression(billing.getReminder());
long nextReminder = exp.getNextValidTimeAfter(new Date()).getTime();
我的想法是检查此“ nextReminder”是否为isToday(),然后创建一些任务。 用Java 11进行检查的最佳方法是什么?
解决方法
您可以使用java.time
进行比较...
有一个Instant
代表一个瞬间,就像一个以毫秒为单位的时间戳一样(⇒您的long nextReminder
)以及OffsetDateTime.now()
代表了现在的 now时刻。 em>和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
也可能是一个明智的选择。
answer by deHaar是正确的。但是,我觉得写这本书是因为在这种情况下,使用Zone ID(而不是Zone Offset)可以使代码更简单,也更容易理解。
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
// A test data
long nextReminder = 1597754387710L;
// Your time-zone e.g. Europe/London
ZoneId zoneId = ZoneId.of("Europe/London");
// Next reminder date
Instant instant = Instant.ofEpochMilli(nextReminder);
LocalDate nextReminderDate = instant.atZone(zoneId).toLocalDate();
// Today at the time-zone of Europe/London
LocalDate today = LocalDate.now(zoneId);
if (today.equals(nextReminderDate)) {
System.out.println("The next reminder day is today");
}
}
}
输出:
The next reminder day is today
,
使用Apache Commons DateUtils.isToday(nextReminder)
使用您自己的方法。
private static final long MILLIS_PER_DAY = 86400000;
public static boolean isToday(long timestamp) {
long now = System.currentTimeMillis();
long today = now.getTime() / MILLIS_PER_DAY;
long expectedDay = timestamp / MILLIS_PER_DAY;
return today == expectedDay;
}
注意:处理日期/时间时,请考虑使用UTC。