Parse time of day string

2019-09-03 02:32发布

问题:

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);