解析时间字符串 [英] Parse time of day string

查看:154
本文介绍了解析时间字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入是一个字符串,如23:55或09:20,即HH:mm格式。我希望字符串以UTC格式指定时间。我想使用java.time将字符串和输出解析为具有指定时间的Instant。如果需要,我可以在字符串中附加一个时区,即23:55 UTC。

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.e。

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

编辑:可能找到解决方案:

Might have found a solution:

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


推荐答案

另一种方法是使用ZonedDateTime:

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

这篇关于解析时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆