在Java中将纪元转换为ZonedDateTime

编程入门 行业动态 更新时间:2024-10-11 01:13:39
本文介绍了在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

本文发布于:2023-11-25 06:41:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628711.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:纪元   转换为   中将   Java   ZonedDateTime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!