如何在特定时区的特定时间(如 12:00:00.000)获取一天中某个时间的 Date 实例?

How to get a Date instance with time of a day at a certain time (like 12:00:00.000) in a specific time zone?

比如,现在越南是2020-03-16 11:23:23.121,但是我的程序在美国是运行,如何获取一个日期实例是2020-03 -16 12:00:00.000 在越南,也就是说,我保持年月日不变,但是小时设置为12,分秒纳秒设置为0,LocalDateTime可以发挥作用吗?

ZonedDateTime

从 java-8 开始,您可以使用 ZonedDateTime 从任何区域获取日期时间

ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.of("Asia/Ho_Chi_Minh"))

您可以使用 with method. Pass the time of day as a LocalTime object obtained by calling LocalTime.of 将时间修改为 12:00:00。在新的 LocalTime 对象中,秒和纳秒默认为零,因此无需将这些参数传递给工厂方法。

dateTime.with( LocalTime.of( 12 , 0 ) )  //2020-03-16T12:00+07:00[Asia/Ho_Chi_Minh]

Java util Date 不会存储任何时区信息,它只代表一个特定的时间(只有 UTC),精度为毫秒。我会建议避免使用遗留 util.Date

ZonedDateTime zdt = ZonedDateTime.of(2020, 3, 16, 12, 0, 0, 0, ZoneId.of("Asia/Ho_Chi_Minh"));

不,不要在这里使用LocalDateTime

can LocalDateTime play a role?

LocalDateTime 不能表示时刻,因为它缺少时区或与 UTC 的偏移量的上下文。所以这正是错误的类用于你的问题。

要表示时刻,时间轴上的特定点,请使用:

  • Instant(始终采用 UTC)
  • OffsetDateTime(带有与 UTC 的偏移量,小时-分钟-秒数)
  • ZonedDateTime(带有分配的时区,在 Continent/Region 中命名)

请参阅正确的 以正确使用 ZonedDateTime 来解决您的问题。

有关详细信息,请参阅