0

I am writing a code for implementing Stop Watch. I capture a moment with System.nanoTime(). But I would also like to convert and store that moment into a date field. When I try to use new Date(long msec), it's giving me some absurd date-time value. Can anyone help me how to get this done?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Plymouth Rock
  • 472
  • 2
  • 6
  • 20
  • 2
    nanotime is not the current time. Use `System.currentTimeMillis()`. – Reut Sharabani Sep 10 '15 at 08:42
  • Can you post code + example of what you get (before and after the conversion)? Have you also tried something like [this](http://javarevisited.blogspot.de/2012/12/how-to-convert-millisecond-to-date-in-java-example.html) (note that it handles milliseconds but you can easily apply this to nanoseconds)? – rbaleksandar Sep 10 '15 at 08:43
  • @ReutSharabani Yeah, that's right. I posted a link to an example. – rbaleksandar Sep 10 '15 at 08:44
  • But can we not able to dynamically find Date from a nanotime? What is the 0th nanosec means then? – Plymouth Rock Sep 10 '15 at 08:44

1 Answers1

2

System.nanoTime is not the current time:

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.

This is why you're experiencing "some absurd date-time value".

Use System.currentTimeMillis if you want the date(s) you've captured as milliseconds (see: unix time):

the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
  • Thanks a lot to all.. got the ans.. so now I am doing like this -- long curMilSec = System.currentTimeMillis(); long nanSec = System.nanoTime(); long startMillis = curMilSec-(nanSec/1000000); ....... new Date(System.nanotime()/ 1000000 + startMillis); – Plymouth Rock Sep 10 '15 at 09:54