Swift: ARKit TimeInterval to Date

Viewed 57

The currentFrame (ARFrame) of ARSession has a timestamp attribute of type TimeInterval which represents the uptime at the moment the frame has been captured.

I need to convert this TimeInterval to the current time domain of the device.

If my assumption about timestamp is correct, adding the kernel BootTime and timestamp together would give me the correct date.

Problem: Adding the kernel BootTime and timestamp together gives me an Date that is not correct. (depending on the device`s last boot time up to 2 days variance)

Current Code:

func kernelBootTime() -> Date {
    var mib = [CTL_KERN, KERN_BOOTTIME]
    var bootTime = timeval()
    var bootTimeSize = MemoryLayout<timeval>.stride

    if sysctl(&mib, UInt32(mib.count), &bootTime, &bootTimeSize, nil, 0) != 0 {
        fatalError("Could not get boot time, errno: \(errno)")
    }

    return Date(timeIntervalSince1970: Double(bootTime.tv_sec) + Double(bootTime.tv_usec) / 1_000_000.0)
}

public func checkTime(_ session: ARSession) {
    guard let frame = session.currentFrame else { return }
    print(Date(timeInterval: frame.timestamp, since: kernelBootTime()))
}
1 Answers

I found the solution.

var refDate = Date.now - ProcessInfo.processInfo.systemUptime

gives you the date of the last device restart

public func checkTime(_ session: ARSession) {
    guard let frame = session.currentFrame else { return }
    print(Date(timeInterval: frame.timestamp, since: refDate))
}

prints the exact time when the image was taken. (in UTC time)

Related