Date 将日期截断为给定时区中一天的开始日期

Date 将日期截断为给定时区中一天的开始日期,date,java-8,timezone,jodatime,Date,Java 8,Timezone,Jodatime,对于给定的时区,我希望将日期时间截断为一天的开始时间。 如果当前时间为Mon Aug 24 15:38:42 America/Los_Angeles,则应将其截断为当天的开始时间Mon Aug 24 00:00:00 America/Los_Angeles,之后应将其转换为等效的UTC时间 我探讨了Joda Time Library、Apache Commons Library和ZoneDateTime提供的方法,但所有这些方法都会截断UTC中的日期时间,而不是特定时区 有人能帮我吗?提前感谢。

对于给定的时区,我希望将日期时间截断为一天的开始时间。 如果当前时间为
Mon Aug 24 15:38:42 America/Los_Angeles
,则应将其截断为当天的开始时间
Mon Aug 24 00:00:00 America/Los_Angeles
,之后应将其转换为等效的UTC时间

我探讨了Joda Time Library、Apache Commons Library和ZoneDateTime提供的方法,但所有这些方法都会截断UTC中的日期时间,而不是特定时区


有人能帮我吗?提前感谢。

您可以使用
ZoneDateTime
。使用
ZonedDateTime
上的
toLocalDate()
获取
LocalDate
然后使用
LocalDate
上的
AtStartDay
ZonedDateTime
实例获取一天的开始

例如:

ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
ZonedDateTime startOfDay = now.toLocalDate().atStartOfDay(now.getZone());

DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME;
System.out.println(now.format(formatter));         // Mon, 24 Aug 2020 10:41:41 -0700
System.out.println(startOfDay.format(formatter));  // Mon, 24 Aug 2020 00:00:00 -0700

您可以使用
ZoneDateTime
。使用
ZonedDateTime
上的
toLocalDate()
获取
LocalDate
然后使用
LocalDate
上的
AtStartDay
ZonedDateTime
实例获取一天的开始

例如:

ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
ZonedDateTime startOfDay = now.toLocalDate().atStartOfDay(now.getZone());

DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME;
System.out.println(now.format(formatter));         // Mon, 24 Aug 2020 10:41:41 -0700
System.out.println(startOfDay.format(formatter));  // Mon, 24 Aug 2020 00:00:00 -0700

ZoneDateTime
在其自己的时区中截断。因此,可以比目前接受的答案(这也是一个好的正确答案)简单一点

输出为:


ZoneDateTime
在其自己的时区中截断。因此,可以比目前接受的答案(这也是一个好的正确答案)简单一点

输出为:

Truncated to start of day: 2020-08-24T00:00-07:00[America/Los_Angeles]
In UTC: 2020-08-24T07:00:00Z