kuki
kuki

Reputation: 13

converting timestamp to nanoseconds

I have a certain value of date and time say 28-3-2012(date) - 10:36:45(time) . I wish to convert this whole timestamp to nanoseconds with the precision of nanoseconds. As in the user would input the time and date as shown but internally i have to be accurate upto nanoseconds and convert the whole thing to nanoseconds to form a unique key assigned to a specific object created at that particular time. Could some one please help me with the same..

Upvotes: 0

Views: 13323

Answers (3)

Bagira
Bagira

Reputation: 2279

I suppose the simplest way would be to use JDK's support for this. Try following

TimeUnit.NANOSECONDS.toNanos(duration)

Here the single parameter duration will be the long value to which you want to convert to NanoSeconds.

Hope this helps.

Upvotes: 0

Wajdy Essam
Wajdy Essam

Reputation: 4340

if you have Date object:

long nanosecond = date.getTime() * 1000000;

or you can parse your time string if its look like (dd/MM/yyyy HH:mm:ss)

 DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
 Date date = df.parse(dateString);
 long nanosecond = date.getTime() * 1000000;

Upvotes: 1

Andreas Dolk
Andreas Dolk

Reputation: 114757

The precision of the sample date is seconds, the representation in long format is a value in millisecond units. You can convert that to nanosecond units by multiplying it with 1,000,000.

But, in fact, it will simply append nine zeros to the oririginal date value and not add any extra information that you'd need to create hashvalues. A Date object has no "hidden" nanosecond precision.


Java offers the method System.nanoTime() which returns a timevalue in nano second units. But we can't wrap it in a Date object without loosing precision. Nevertheless, it may help in your case to create unique "time values".

Upvotes: 2

Related Questions