/**
* <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);
}
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");
}
}
}
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;
}
3条答案
按热度按时间jfgube3f1#
你可以用
java.time
作为比较。。。有一个
Instant
表示时间上的某个时刻,就像时间戳以毫秒表示一样(⇒ 你的long nextReminder
)以及OffsetDateTime.now()
现在和现在LocalDate
仅作为描述日期部分的部分。你可以看看
nextReminder
今天是用这样的方法:然后就这样说吧
它将使用系统的时间偏移。也许 吧,
ZoneOffset.UTC
也可能是个明智的选择。pgx2nnw82#
德哈尔的回答是正确的。但是,我觉得编写这个代码是因为在本例中,使用zone id(而不是zone offset)使代码更简单,也更容易理解。
输出:
j8ag8udp3#
使用apache commons
DateUtils.isToday(nextReminder)
用你自己的方法。注意:使用日期/时间时,请考虑使用utc。