【问题标题】:find ZonedDateTime is today, yesterday or else查找 ZonedDateTime 是今天、昨天还是其他
【发布时间】:2023-01-30 23:00:03
【问题描述】:

我有一个 ZonedDateTime 对象列表(Eg. 2023-01-01T20:40:01.001+05:30[Asia/Kolkata])

我需要编写一个方法来获得以下结果。

if ZonedDateTime is today -> return "Today"
if ZonedDateTime is yesterday -> return "Yesterday"
else -> return ZonedDateTime in "yyyy-MM-dd" format -> (Eg. DateTimeFormatter.ofPattern("yyyy-MM-dd").format(zonedDateTime))

如何计算 ZonedDateTime 是今天、明天还是其他时间?与 ZonedDateTime 对象处于同一时区的“今天”。

【问题讨论】:

  • “今天是”在哪个时区?这里有两个同样合理的选择...... - 系统时区,或分区日期时间自己的时区
  • @Sweeper 与 ZonedDateTime 对象相同的时区

标签: kotlin date date-format java-time zoneddatetime


【解决方案1】:

在大多数情况下,您实际上不需要使用ZonedDateTimes。只需在所需的ZoneId 中找出今天是星期几,然后从该点开始使用LocalDates。

检查toLocalDate()是否等于今天,或者它是否等于今天减去一天。

public static String getRelativeDateString(ZonedDateTime zdt) {
    var today = LocalDate.now(zdt.getZone());
    var ld = zdt.toLocalDate();

    if (ld.equals(today)) {
        return "Today";
    } else if (ld.equals(today.minusDays(1))) {
        return "Yesterday";
    } else {
        return ld.format(DateTimeFormatter.ISO_LOCAL_DATE /* or another formatter */);
    }
}

【讨论】:

  • 对于所需的格式,您可以简单地返回ld.toString()
  • @ArvindKumarAvinash 我知道,但我的习惯是只将它用作调试工具并始终使用 format(DateTimeFormatter) 进行显示,因为后者更方便切换到不同的格式或使用不同的语言环境,而且通常更通用.
  • @Sweeper 谢谢,它帮助解决了我的问题。
  • @Arvind Kumar Avinash 感谢您提供额外信息。
猜你喜欢
  • 1970-01-01
  • 2014-10-26
  • 2011-05-02
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-12
  • 1970-01-01
相关资源
最近更新 更多