NSTimeInterval to unix timestamp

假装没事ソ 提交于 2019-12-19 03:07:19

问题


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!


回答1:


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;



回答2:


I imagine it is supposed to be used as a relative measure to allow you to sequence motion events correctly, so they went for as lightweight an implementation as possible.

I can't think why you'd need the actual date and time of a motion event as they are all dealt with pretty much straight away. But if you really wanted to, you'd have to get the timestamp of one event, use that with the current date to work out the base date, and then use your base date to derive the actual time of subsequent events.



来源:https://stackoverflow.com/questions/7576017/nstimeinterval-to-unix-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!