gpt4 book ai didi

java - 测试 Java 7 中的 Unix 时间戳是否是今天

转载 作者:行者123 更新时间:2023-12-02 12:46:18 24 4
gpt4 key购买 nike

我需要检查 Unix 时间戳(存储为 long)是否代表今天(在我的时区)。这就是我所在的位置,但看起来不太优雅:

Calendar tokenTimestamp = Calendar.getInstance();
tokenTimestamp.setTimeInMillis(foo.getDateTimeCreated());

Calendar now = Calendar.getInstance();

if (tokenTimestamp.get(Calendar.DAY_OF_MONTH) != now.get(Calendar.DAY_OF_MONTH)
|| tokenTimestamp.get(Calendar.MONTH) != now.get(Calendar.MONTH)
|| tokenTimestamp.get(Calendar.YEAR) != now.get(Calendar.YEAR)) {
// Not today...
}

是否有更正确和/或更优雅的方法来做到这一点?

最佳答案

在 Java 7 的日历中,这可能是您能做的最好的事情了。我只是添加一点细节,指定您想要日期的时区(如 @Ole V.V.'s comment 所指出的):

// current date in system default timezone
Calendar.getInstance(TimeZone.getDefault());
// current date in Europe/London timezone
Calendar.getInstance(TimeZone.getTimeZone("Europe/London"));

也可以使用IANA timezones names (始终采用Continent/City 格式,例如America/Sao_PauloEurope/Berlin)。避免使用 3 个字母的缩写(例如 CSTPST),因为它们是 ambiguous and not standard .

<小时/>

旧类(DateCalendarSimpleDateFormat)有 lots of problemsdesign issues ,并且它们正在被新的 API 取代。

对于 Android,您可以使用 ThreeTen Backport ,Java 8 的新日期/时间类的一个很好的向后移植,以及 ThreeTenABP (更多关于如何使用它 here )。

下面的所有类都位于org.thirden.bp包下。当您仅比较日期(日/月/年)时,我使用 org. Threeten.bp.LocalDate 类。我还使用 org.thirden.bp.ZoneId 指定时区,并使用 org. Threeten.bp.Instant 类来转换 long 毫秒日期值:

// millis value
long millis = 1498499869249L;

// get the date in system default timezone
LocalDate dt = Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).toLocalDate();
// check if it's equals to today
System.out.println(dt.equals(LocalDate.now(ZoneId.systemDefault())));

如果您想要不同的时区,请将 ZoneId.systemDefault() 替换为 ZoneId.of("Europe/London") (或任何您想要的时区名称 - 您可以得到一个通过调用 ZoneId.getAvailableZoneIds() 列出所有可用时区。

并且不要忘记在两行中使用相同的时区,以确保您比较的是正确的值。

<小时/>

如果您想比较日期和时间(日/月/年和时/分/秒),您可以使用 org.thirden.bp.LocalDateTime 代替:

// get the date in system default timezone
LocalDateTime dt = Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).toLocalDateTime();
// check if it's equals to today
System.out.println(dt.equals(LocalDateTime.now(ZoneId.systemDefault())));

关于java - 测试 Java 7 中的 Unix 时间戳是否是今天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44762934/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com