在Java中将纪元转换为ZonedDateTime [英] converting epoch to ZonedDateTime in Java

查看:304
本文介绍了在Java中将纪元转换为ZonedDateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中将类似 1413225446.92000 的时代转换为 ZonedDateTime

How to convert epoch like 1413225446.92000 to ZonedDateTime in java?

给出的代码期望 long 值,因此对于上面给出的值,这将引发 NumberFormatException

The code given expects long value hence this will throw NumberFormatException for the value given above.

ZonedDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(dateInMillis)), ZoneId.of(TIME_ZONE_PST));


推荐答案

罗勒·布尔克的答案是一个很好的答案。从小数部分中取出纳秒到一个纳秒整数可能会导致一个或两个陷阱。我建议:

Basil Bourque’s answer is a good one. Taking out the nanoseconds from the fractional part into an integer for nanoseconds may entail a pitfall or two. I suggest:

    String dateInMillis = "1413225446.92000";
    String[] secondsAndFraction = dateInMillis.split("\\.");
    int nanos = 0;
    if (secondsAndFraction.length > 1) { // there’s a fractional part
        // extend fractional part to 9 digits to obtain nanoseconds
        String nanosecondsString
                = (secondsAndFraction[1] + "000000000").substring(0, 9);
        nanos = Integer.parseInt(nanosecondsString);
        // if the double number was negative, the nanos must be too
        if (dateInMillis.startsWith("-")) {
            nanos = -nanos;
        } 
    }
    ZonedDateTime zdt = Instant
            .ofEpochSecond(Long.parseLong(secondsAndFraction[0]), nanos)
            .atZone(ZoneId.of("Asia/Manila"));
    System.out.println(zdt);

此打印文件

2014-10-14T02:37:26.920+08:00[Asia/Manila]

纳秒不需要64位,所以我只是使用 int

We don’t need 64 bits for the nanoseconds, so I am just using an int.

假设:我假设您的字符串包含浮点数,并且可以对它进行签名,例如 -1.50 表示前一秒半时代。如果有一天的纪元用科学记数法(1.41322544692E9)表示,则上述方法将无效。

Assumption: I have assumed that your string contains a floating-point number and that it may be signed, for example -1.50 would mean one and a half seconds before the epoch. If one day your epoch time comes in scientific notation (1.41322544692E9), the above will not work.

请在地区/城市中替换您所需的时区格式(如果不是亚洲/马尼拉),例如America / Vancouver,America / Los_Angeles或Pacific / Pitcairn。避免使用三个字母缩写,例如PST,它们是模棱两可的,通常不是真实的时区。

Please substitute your desired time zone in the region/city format if it didn’t happen to be Asia/Manila, for example America/Vancouver, America/Los_Angeles or Pacific/Pitcairn. Avoid three letter abbreviations like PST, they are ambiguous and often not true time zones.

这篇关于在Java中将纪元转换为ZonedDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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