Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 730
Alex Stone Avatar asked Sep 27 '11 21:09

Alex Stone


People also ask

Is UTC Unix time?

Unix time is a way of representing a timestamp by representing the time as the number of seconds since January 1st, 1970 at 00:00:00 UTC. One of the primary benefits of using Unix time is that it can be represented as an integer making it easier to parse and use across different systems.

Are all Unix timestamps in UTC?

Unix timestamps are always based on UTC (otherwise known as GMT). It is illogical to think of a Unix timestamp as being in any particular time zone. Unix timestamps do not account for leap seconds.

How do you convert date to epoch time?

Convert from human-readable date to epochlong epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000; Timestamp in seconds, remove '/1000' for milliseconds. date +%s -d"Jan 1, 1980 00:00:01" Replace '-d' with '-ud' to input in GMT/UTC time.


1 Answers

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;
like image 183
Kay Avatar answered Sep 19 '22 04:09

Kay