如何让PST到达mid

时间:2016-08-31 11:13:46

标签: java java-time timezone-offset

我需要在现在和午夜之间获得美国/洛杉矶"" America / Los_Angeles" (PST)。

midnightAtPST = ???;

long millis = ChronoUnit.MILLIS.between(now, midnightAtPST) ???

这就是我现在所拥有的,它给出了一个不正确的值:

LocalDateTime midnight = LocalDateTime.now().toLocalDate().atStartOfDay().plusDays(1);
Instant midnigthPST = midnight.atZone(ZoneId.of("America/Los_Angeles")).toInstant();
Instant now = LocalDateTime.now().toInstant(ZoneOffset.UTC);

long millis = ChronoUnit.MILLIS.between(now, midnigthPST);

2 个答案:

答案 0 :(得分:1)

Since you're interested for the time in a specific zone, do not use a LocalDateTime, which does not have the notion of timezones, but use a ZonedDateTime.

You can obtain the current date in a given zone with the ZonedDateTime.now(zone) static factory. Then, you can have the date at midnight (on the next day) in a given timezone with the method atStartOfDay(zone) on the type LocalDate.

ZoneId zoneId = ZoneId.of("America/Los_Angeles");
ZonedDateTime now = ZonedDateTime.now(zoneId);
ZonedDateTime midnight = LocalDate.now().atStartOfDay(zoneId).plusDays(1);

long millis = ChronoUnit.MILLIS.between(now, midnight);

This will correctly return the number of milliseconds between the current date and the start of the next day in Los Angeles.

答案 1 :(得分:0)

您的方法很好,除了now时刻,您从时区转换为UTC时区,给出了您不想要的偏移。

这应该按照您的预期运作:

Instant now = Instant.now();