[英]Java - Get LocalDateTime from Double
I am receiving this value in a Json format:我以 Json 格式接收此值:
{"time": 1643213994.7369497}
This time value is supposed to produce a DateTime value like this:这个时间值应该产生一个像这样的 DateTime 值:
2021-08-12T03:03:31.656050+00:00
How can I get this value parsed into a LocalDateTime
object or the format above?如何将此值解析为
LocalDateTime
object 或上述格式?
Assuming that number represents an Epoch Time, have you tried (in Java 8+) rounding it up and using假设该数字代表一个纪元时间,您是否尝试过(在 Java 8+ 中)将其四舍五入并使用
LocalDateTime myLocalDateTime = Instant.ofEpochMilli(yourTimeHere).atZone(ZoneId.systemDefault()).toLocalDateTime();
for example?例如?
You might want to replace ZoneId.systemDefault()
with the ZoneID
that is relevant to you.您可能希望将
ZoneId.systemDefault()
替换为与您相关的ZoneID
。
Since there's no timezone / offset information available in your source, you can convert it to an Instant
and convert that to a ZonedDateTime
or OffsetDateTime
later.由于您的源中没有可用的时区/偏移信息,您可以将其转换为
Instant
并稍后将其转换为ZonedDateTime
或OffsetDateTime
。
A double like yours can be converted to an Instant using this method:可以使用以下方法将像您这样的 double 转换为 Instant:
public static Instant toInstant(double value) {
final long epochSecond = (long) Math.floor(value);
final long nanoAdjustment = (long) ((value % 1.0) * 1000_000_000.0);
return Instant.ofEpochSecond(epochSecond, nanoAdjustment);
}
You can then later convert it to a ZonedDateTime
like this:然后,您可以稍后将其转换为
ZonedDateTime
,如下所示:
Instant yourInstant = ...;
ZonedDateTime zdt = yourInstant.atZone(ZoneId.systemDefault());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.