Search code examples
iostimestampnstimeintervalcore-motion

NSTimeInterval to unix timestamp


I'm getting CMDeviceMotion objects from CMMotionManager. One of the properties of the CMDeviceMotion is timestamp, which is expressed as a NSTimeInterval (double). This allows for "sub millisecond" timestamp precision, according to documentation.

[motionManager startDeviceMotionUpdatesToQueue:motionQueue withHandler:^(CMDeviceMotion *motion, NSError *error) { 
  NSLog(@"Sample: %d Timestamp: %f ",counter,  motion.timestamp);
}

Unfortunately, NSTimeInterval is calculated since last device boot, posing significant challenges to using it in its raw form.

Does anyone have a working code to convert this NSTimeInterval into a Unix like timestamp (UTC timezone)?

Thank you!


Solution

  • I had a similar problem when comparing magnetometer values with CoreMotion events. If you want to transform these NSTimeIntervals you just need to calculate the offset once:

    // during initialisation
    
    // Get NSTimeInterval of uptime i.e. the delta: now - bootTime
    NSTimeInterval uptime = [NSProcessInfo processInfo].systemUptime;
    
    // Now since 1970
    NSTimeInterval nowTimeIntervalSince1970 = [[NSDate date] timeIntervalSince1970];
    
    // Voila our offset
    self.offset = nowTimeIntervalSince1970 - uptime;