Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert nanoseconds since 1904 to a valid java date

Tags:

java

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?

like image 470
Marcio Avatar asked Jul 26 '13 19:07

Marcio


1 Answers

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

like image 58
Rohit Jain Avatar answered Sep 18 '22 13:09

Rohit Jain