如何将NSString hexInterval转换为NSTimeInterval进行日期转换

时间:2015-06-09 16:40:05

标签: ios objective-c nsdate nstimeinterval

目前,我正在使用以下格式的现有NSDate数组:

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

日期以4ec2acf0

等格式输出

我的目标是将这些转回NSDates,因为它们来自NSTimeInterval,我想知道如何将它转回NSTimeIntervals,因为我拥有的只是这些8个字符的NSStrings。

我的目标是:

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

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用NSScanner解析十六进制,如下所示:

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];

请注意,此方法会截断NSTimeInterval的时间部分。当您在此行上将NSTimeInterval转换为int时,会发生这种情况:

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