Date: 2025aug21
Language: Java
Q. Java: Convert nanoTime() to currentTimeMillis()
A. When converting, you need to be aware that they are reporting the time from different
stating points. So you cannot simply divide the nanotime by 10^6 to get the milliseconds.
In the solution below, we do _getDiffMs() to see how many milliseconds are between the current
times and save that do be later used as an offset:
import java.lang.System;
class Main {
private static long _getDiffMs() { // Just done once (at start up)
final long ms = System.currentTimeMillis();
final long ns = System.nanoTime();
return ns / 1_000_000 - ms;
}
private static long gDiffMs = _getDiffMs();
public static long nanoToMilli(final long nanoIn) { // The function we're demo-ing
final long ms = nanoIn / 1_000_000;
return ms - gDiffMs;
}
// Testing
public static void main(String args[]) {
for (int i = 0; i < 10; i++) {
final long ns = System.nanoTime();
final long ms1 = System.currentTimeMillis();
final long ms2 = nanoToMilli(ns); // There is where we call our function
System.out.println("current ms=" + ms1);
System.out.println("nano to ms=" + ms2);
if (ms1 == ms2) {
System.out.println("Converted ns is the SAME as ms"); // It worked
}
else {
System.out.println("Converted ns is DIFFERENT then ms");
}
try {
Thread.sleep(1000);
}
catch(InterruptedException ex) {
// Ignore
}
System.out.println();
}
}
}
Outputs:
current ms=1755807715186
nano to ms=1755807715186
Converted ns is the SAME as ms
current ms=1755807716188
nano to ms=1755807716188
Converted ns is the SAME as ms
current ms=1755807717189
nano to ms=1755807717189
Converted ns is the SAME as ms
current ms=1755807718189
nano to ms=1755807718189
Converted ns is the SAME as ms
...