3
votes

When scanning for Bluetooth Low Energy packets I receive ScanCallback with ScanResult being set. I can get "Device timestamp when the scan result was observed" with result.getTimestampNanos() but this time is not aligned with the Systems.nanoTime(). Is there a way to convert from one to the other?

2

2 Answers

5
votes

Use the following code to convert the getTimestampNanos() to system millis by using SystemClock.elapsedRealtime():

long rxTimestampMillis = System.currentTimeMillis() - 
                         SystemClock.elapsedRealtime() +
                         scanResult.getTimestampNanos() / 1000000;

This can be converted easily to a Date object:

Date rxDate = new Date(rxTimestampMillis);

Then you then get the time as a string:

String sDate = new SimpleDateFormat("HH:mm:ss.SSS").format(rxDate);
1
votes

More elegant way to do that

long actualTime = System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(SystemClock.elapsedRealtimeNanos() - scanResult.getTimestampNanos(), TimeUnit.NANOSECONDS)```