4
votes

I receive a CMLogItem from a CoreMotion query in swift (could be accelerometer, gyroscope). Now, I want to get the timestamp of that sample, preferably as a Date() object. CMLogItems have a property .timestamp of type TimeInterval.

The documentation tells me the following:

The CMLogItem class defines a read-only timestamp property that records the time a motion-event measurement was taken.

However, I am not sure how to convert this timestamp to a Date() object because I dont know what the timestamp is referring to.

Another documentation says:

The timestamp is the amount of time in seconds since the device booted.

But this seems really weird and I dont understand why apple would create such an inconsistent and complicated API.

1

1 Answers

-1
votes

I think I figured it out. The documentation is just wrong here. It is not the "time in seconds since the device booted" — it is indeed the time since their reference date.

Fix:

extension CMLogItem {
    func startTime() -> Date {
        #if os(watchOS)
        return Date(timeIntervalSinceReferenceDate: self.timestamp)
        #else
        let systemRebootTime = Date(timeIntervalSinceNow: -ProcessInfo.processInfo.systemUptime)
        return systemRebootTime.addingTimeInterval(self.timestamp)
        #endif
    }
}