Reputation: 391
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?
Upvotes: 4
Views: 2464
Reputation: 974
More elegant way to do that
long actualTime = System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(SystemClock.elapsedRealtimeNanos() - scanResult.getTimestampNanos(), TimeUnit.NANOSECONDS)```
Upvotes: 1
Reputation: 2206
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);
Upvotes: 7