Parse time of day string

五迷三道 提交于 2020-01-06 14:07:10

问题


Input is a string such as "23:55" or "09:20", i.e. in the "HH:mm" format. I want the string to specify the time of day in UTC. I want to use java.time to parse the string and the output to be an Instant with the specified time of day today. If needed I can append a time zone to the string, i.e. "23:55 UTC".

I want to use the resulting instant to calculate the number of nanos between now and the mentioned instant. I.e.

Duration.between(Instant.now(), resultingInstant).toNanos();

Edit: Might have found a solution:

resultingInstant = LocalTime.parse("23:55").atDate(LocalDate.now(ZoneOffset.UTC)).toInstant(ZoneOffset.‌​UTC)

回答1:


An alternative is to use a ZonedDateTime:

import static java.time.ZoneOffset.UTC;
import static java.time.temporal.ChronoUnit.NANOS;

LocalDate today = LocalDate.now(UTC);
ZonedDateTime resultingDate = ZonedDateTime.of(today, LocalTime.parse("23:55"), UTC);
long nanos = NANOS.between(ZonedDateTime.now(), resultingDate);


来源:https://stackoverflow.com/questions/29539404/parse-time-of-day-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!