将自1904年以来的纳秒转换为有效的java日期

Mar*_*cio 7 java date

我有一个数字代表自1904年1月1日凌晨12:00以来的纳秒数.我希望实例化一个java.util.Date表示该日期的对象.我该怎么办?

Roh*_*ain 5

首先需要将表示纳秒数字转换为毫秒.

然后,对于给定的日期字符串,获取自unix时间Epoch以来的总毫秒数,然后将之前转换为毫秒的数字添加到它.

这是工作代码:

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);
Run Code Online (Sandbox Code Playgroud)

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