4

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?

hebeha
  • 362
  • 2
  • 17

2 Answers2

7

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);
Glenn
  • 1,996
  • 2
  • 24
  • 32
  • Not sure why you prefixed your variables with `rx` or even `s`, but I don't think we need RxJava for this – Louis CAD Feb 23 '17 at 11:05
  • 2
    tx and rx are common abbreviations for receive and transmit. I pasted this code from a source file which was using both a 'tx' and an 'rx' timestamp. In this case the question was about receive timestamps so I left the rx prefix. – Glenn Feb 24 '17 at 17:25
1

More elegant way to do that

long actualTime = System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(SystemClock.elapsedRealtimeNanos() - scanResult.getTimestampNanos(), TimeUnit.NANOSECONDS)```
Dmytro Batyuk
  • 957
  • 8
  • 15
  • How could I scan periodically with different timestamps for Wifi since I only receive only one RSSI at one time for each scan – Reyha Nov 02 '21 at 02:59