How to convert CellInfo timestamp to actual date?

491 views Asked by At

I am using TelephonyManger.getAllCellInfo to gather information about nearby cells. I noticed that CellInfo contains a field named mTimestamp, which according to documentation is:

Approximate time of this cell information in nanos since boot

Now, I want to convert this time to an actual timestamp, which will give me the specific date on which the sample was taken.

Is doing it as such: return System.currentTimeMillis() - timestampFromBootInNano / 1000000L; the correct way to convert it?

1

There are 1 answers

2
CommonsWare On BEST ANSWER

No. mTimestamp is measured in nanoseconds since the device was booted. System.currentTimeMillis() is measured in milliseconds since midnight January 1, 1970.

You can:

  • Subtract mTimestamp from SystemClock.elapsedRealtimeNanos(), to determine how many nanoseconds ago the timestamp represents

  • Convert that to milliseconds to determine how many milliseconds ago the timestamp represents

  • Subtract that from System.currentTimeMillis() to determine the time when the timestamp was made

So, that gives us:

long millisecondsSinceEvent = (SystemClock.elapsedRealtimeNanos() - timestampFromBootInNano) / 1000000L;
long timeOfEvent = System.currentTimeMillis() - millisecondsSinceEvent;

timeOfEvent can now be used with things like java.util.Calendar, ThreeTenABP, etc.