【问题标题】:How can I get a specific time Today in UTC java如何在UTC java中获得今天的特定时间
【发布时间】:2018-02-09 15:21:53
【问题描述】:

我正在尝试获取“今天”的 UTC 特定时间。 说世界标准时间下午 5 点 Instant.now().truncatedTo(ChronoUnit.DAYS).plus(1, ChronoUnit.DAYS) 或者 Instant.now().plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.DAYS) 我相信这让我到了当天的午夜。我只是扩展这个 Instant.now().truncatedTo(ChronoUnit.DAYS).plus(1, ChronoUnit.DAYS).minus(7, ChronoUnit.HOURS); 或者有没有更好的方法来做到这一点。

【问题讨论】:

  • 或者更好,下次是世界标准时间下午 5 点。
  • 无法保证从瞬间通过算术得到“下午 5 点”。
  • 谢谢。您建议的任何其他方法来获取“今天”的特定 UTC 时间。
  • @Holger,Instant也支持with(LocalTime),所以应该不会很难。
  • 我的错:Instant 实际上不支持。出于某种原因,不支持 nano-of-day chrono 字段,这是 LocalTime 用于将自身表示为单个值的字段。

标签: java datetime java-8 java-time java.time.instant


【解决方案1】:

应该是这样的

ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
// this would be the today (might be in the past)
ZonedDateTime result = now.with(LocalTime.of(17, 0));
if (result.isBefore(now)) {
  // This would be "next time it is 5 o-clock".
  result = result.plusDays(1);
}
// if you really want an Instant out of it.
return result.toInstant();

【讨论】:

  • 谢谢!我会试一试。
  • OffsetDateTime 也可以。否则一个很好的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
  • 1970-01-01
  • 2022-12-03
相关资源
最近更新 更多