How to turn NSString hexInterval into NSTimeInterval for date conversion

201 views Asked by At

Currently, I am working with an existing array of NSDates in the following format:

NSDate *today = [NSDate date]; //today is used as an example
NSTimeInterval interval = [today timeIntervalSince1970];
NSString *hexInterval = [NSString stringWithFormat:@"%08x", (int)interval];
NSLog(@"hexInterval %@", hexInterval);

The dates are outputted in a format such as 4ec2acf0.

My goal is to turn these back into NSDates, as since they came from NSTimeInterval, I was wondering how I could turn it back into NSTimeIntervals given that all I have are these 8-character NSStrings.

My goal is:

//Turn NSString into NSTimeInterval here, then:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];

Thanks!

1

There are 1 answers

1
Sergey Kalinichenko On BEST ANSWER

You can parse hex with NSScanner, like this:

unsigned res = 0;
NSScanner *scanner = [NSScanner scannerWithString:hexInterval];
[scanner scanHexInt:&res];
NSTimeInterval interval = (NSTimeInterval)res;
// Once you have an interval, use your code:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];

Note that this approach truncates the time portion of NSTimeInterval. This happens at the point when you convert NSTimeInterval to int on this line:

NSString *hexInterval = [NSString stringWithFormat:@"%08x", (int)interval];