convert nanoseconds since 1904 to a valid java date

烈酒焚心 提交于 2020-04-06 05:15:01

问题


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?


回答1:


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

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.

Here's the working code:

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);

Add an import java.util.concurrent.TimeUnit;.




回答2:


I think it is trivial:

final GregorianCalendar startDate = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
startDate.clear();
startDate.set(1904, Calendar.JANUARY, 1);
final long startMillis = startDate.getTimeInMillis();
new Date(nanos / 1000 / 1000 + startMillis)



回答3:


Date date = new Date(new Date().getTime()-(time in nanoseconds/(1000*1000)));

what's wrong in using this? I tested with a value of "time in nanoseconds" for June 8th 1926 and it works. and date format has nothing to do with it, the underlying milliseconds value representing the time is what is required.




回答4:


First of all java.util.Date

Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

So, if you have variable milliseconds

  1. Somehow calculate number of milliseconds between your date and Jan 1, 1970 (Unix epoch) diff

  2. Use Date(long) constructor

    new Date(milliseconds - diff);
    


来源:https://stackoverflow.com/questions/17889852/convert-nanoseconds-since-1904-to-a-valid-java-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!