将自1904年以来的纳秒转换为有效的Java日期 [英] convert nanoseconds since 1904 to a valid java date

查看:55
本文介绍了将自1904年以来的纳秒转换为有效的Java日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字,它表示自1904年1月1日凌晨12:00(世界标准时间)以来的纳秒数.我希望实例化表示该日期的 java.util.Date 对象.我应该如何进行?

I have a number representing the number of nanoseconds since 12:00 a.m., January 1, 1904, universal time. I wish to instantiate a java.util.Date object representing that date. How should I proceed?

推荐答案

您首先需要将代表 nanoseconds number 转换为毫秒.

You first need to convert your number representing nanoseconds to milliseconds.

然后对于给定的日期字符串,获取自unix时间 Epoch 以来的毫秒总数,然后向其添加更早转换为毫秒的数字.

Then for the given date string, get the total number of milliseconds since the unix time Epoch, and then add the number earlier converted to milliseconds to it.

这是工作代码:

String target = "1904/01/01 12:00 AM";  // Your given date string
long nanoseconds = ...;   // nanoseconds since target time that you want to convert to java.util.Date

long millis = TimeUnit.MILLISECONDS.convert(nanoseconds, TimeUnit.NANOSECONDS); 

DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd hh:mm aaa");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = formatter.parse(target);

long newTimeInmillis = date.getTime() + millis;

Date date2 = new Date(newTimeInmillis);

System.out.println(date2);

添加 import java.util.concurrent.TimeUnit; .

这篇关于将自1904年以来的纳秒转换为有效的Java日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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