2

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?

Keselme
  • 3,779
  • 7
  • 36
  • 68

1 Answers1

3

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Do you know if the CellInfo is constantly updated if the phone is stationary, meaning it stays in the same spot for some time? I noticed that every time I accessed the mTimestamp of CellInfo it was different every time. – Keselme Nov 06 '18 at 08:30
  • @Keselme: I have not experimented much with this API. My gut instinct, though, matches what you see: it is updated frequently, based on signals received by in-range towers. – CommonsWare Nov 06 '18 at 11:47