I want to convert the result of System.nanoTime()
to a date.
public void tempBan(Player p, Player banner, int timeInSeconds){
Long timeInNano = (long) (timeInSeconds * 10^9);
int newTime = (int) (System.nanoTime() + timeInNano);
// here I want to convert newTime to a date
}
I have converted the seconds into nanoseconds by multiplying by 10^9. Now I need to convert the current system time plus the parameter which I converted into nanoseconds into a date.
Unfortunately,
System.nanoTime()
is not what you want for this.To quote the JavaDoc:
You probably want
System.currentTimeMillis()
, in which case you can usenew Date(System.currentTimeMillis() + milliseconds)
to get the date for that number of milliseconds in the future.While you could then subtract
System.nanoTime()
, scale the value, and addSystem.currentTimeMillis()
to have a similar result... since you're addingSystem.nanoTime()
anyway and therefore have the original number of seconds, you could just useSystem.currentTimeMillis()
directly.You can convert it into system time using the below code
Explanation:
System.nonoTime() is a monotonic time that increases only, it has no idea of what time it is right now, but it would only increase regardless. So it is a good way for measuring elapsing time. But you can not convert this into a sensible time as it has no reference to the current time.
The provided method is a way to convert your stored nano time into a sensible time. First, you have a timeMs that is in nano time that you would like to convert. Then, you created another nanotime (i.e refMonoMs) and another System.currentTimeMillis() (i.e refUnixMx). Then you minus refMonoMs from the timeMs, and add the reference back into it to get the sensible time back.