java - Java 11 时间 - 今天是(长)时间戳
问题描述
我在 mongo 文档字段中保存了一个 cronjob 字符串。我得到下一个有效(长时间)时间
CronExpression exp = new CronExpression(billing.getReminder());
long nextReminder = exp.getNextValidTimeAfter(new Date()).getTime();
我的想法是检查这个“nextReminder”是否是今天()然后创建一些任务。使用 java 11 检查它的最佳方法是什么?
解决方案
你可以拿来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
也可能是一个明智的选择。
推荐阅读
- python - Azure /bin/sh 中的 Docker 容器:1:[gunicorn,:未找到
- vue.js - Storage.put() 抛出 - AWSS3Provider - 上传错误 TypeError:无法读取未定义的属性“byteLength”
- javascript - 如何解决 vue 键盘事件绑定问题?
- terraform - 使用 terraform 使用预留实例创建 EKS
- flutter - 检测进入页面事件 Flutter
- javascript - 如何使用node.js在axios请求中添加带有formData的文件
- r - 如何在 R 中排除具有相同 ID 的调查中的用户进行计算?
- javascript - 如何在 gtmetrix 中快速加载网站图标
- excel - 几次迭代后从 SAP 导出的文件错误中复制数据
- c++ - 为什么在 C++23 中 allocate_at_least()?