首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何确定ZonedDateTime是否是“今日”?

如何确定ZonedDateTime是否是“今日”?
EN

Stack Overflow用户
提问于 2017-04-18 15:10:19
回答 1查看 7.5K关注 0票数 12

我以为这已经被问到了,但我找不到anything

使用java.time,确定给定的ZonedDateTime是否为“今天”的最佳方法是什么?

我想出了至少两种可能的解决方案。我不确定这些方法是否有任何漏洞或缺陷。基本上,这样做的目的是让java.time自己解决问题,而不是自己做任何数学运算:

代码语言:javascript
复制
/**
 * @param zonedDateTime a zoned date time to compare with "now".
 * @return true if zonedDateTime is "today".
 * Where today is defined as year, month, and day of month being equal.
 */
public static boolean isZonedDateTimeToday1(ZonedDateTime zonedDateTime) {
    ZonedDateTime now = ZonedDateTime.now();

    return now.getYear() == zonedDateTime.getYear()
            && now.getMonth() == zonedDateTime.getMonth()
            && now.getDayOfMonth() == zonedDateTime.getDayOfMonth();
}


/**
 * @param zonedDateTime a zoned date time to compare with "now".
 * @return true if zonedDateTime is "today". 
 * Where today is defined as atStartOfDay() being equal.
 */
public static boolean isZoneDateTimeToday2(ZonedDateTime zonedDateTime) {
    ZonedDateTime now = ZonedDateTime.now();
    LocalDateTime atStartOfToday = now.toLocalDate().atStartOfDay();

    LocalDateTime atStartOfDay = zonedDateTime.toLocalDate().atStartOfDay();

    return atStartOfDay == atStartOfToday;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-18 15:13:54

如果您的意思是今天在默认时区:

代码语言:javascript
复制
return zonedDateTime.toLocalDate().equals(LocalDate.now());

//you may want to clarify your intent by explicitly setting the time zone:
return zonedDateTime.toLocalDate().equals(LocalDate.now(ZoneId.systemDefault()));

如果您指的是与ZonedDateTime位于同一时区的今天:

代码语言:javascript
复制
return zonedDateTime.toLocalDate().equals(LocalDate.now(zonedDateTime.getZone()));
票数 27
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43475924

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档