简体   繁体   English

Java - 从 Double 获取 LocalDateTime

[英]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并稍后将其转换为ZonedDateTimeOffsetDateTime

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.

相关问题 如何从 Java 中的数组获取最小 LocalDateTime - How to get minimum LocalDateTime from array in Java "如何从 Java 8 中的 LocalDateTime 获取毫秒数" - How to get milliseconds from LocalDateTime in Java 8 如何在 Java 8 上使用 LocalDateTime.now() 获取当前的 LocalDateTime 包括秒数 - How to get the current LocalDateTime including seconds with LocalDateTime.now() on Java 8 解析 LocalDateTime (Java 8) 时无法从 TemporalAccessor 获取 LocalDateTime - Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8) 如何在返回类型为 LocalDateTime 的方法中从 LocalDateTime 对象中获取第二个? - How to get the second from LocalDateTime objects in a method with return type LocalDateTime? Java(Joda):从LocalDateTime午夜开始经过的秒数 - Java (Joda): Seconds from midnight of LocalDateTime Spring MVC中来自LocalDateTime(java 8)的Json字符串 - Json string from LocalDateTime(java 8) in Spring MVC Java LocalDateTime 从 UTC 时区中删除毫秒 - Java LocalDateTime remove the milliseconds from UTC timezone 使用杰克逊310 +弹簧启动,得到错误“无法从字符串反序列化类型为java.time.LocalDateTime的值” - Get error “Can not deserialize value of type java.time.LocalDateTime from String” with jackson 310 + Spring boot 如何从TemporalAccessor获取ZoneId,LocalDateTime和Instant - How to get ZoneId, LocalDateTime and Instant from TemporalAccessor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM