[英]How to parse Unix timestamp from JSON in iOS?
我从某些RESTful服务获得以下格式的时间戳:
"/Date(1357306469510+0100)/"
我发现一些帖子提供了解析此代码并创建其等效NSDate
对象的代码,例如:
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
NSInteger startPosition = [jsonDate rangeOfString:@"("].location + 1;
NSTimeInterval unixTime = [[jsonDate substringWithRange:NSMakeRange(startPosition, 13)] doubleValue] / 1000;
NSDate *date = [[NSDate dateWithTimeIntervalSince1970:unixTime] dateByAddingTimeInterval:offset];
但它似乎无法处理服务器时间戳的时区(+0100)。
有人可以提供完整的解决方案,还是告诉我在哪里可以找到它?
提前致谢
下面的代码应该工作。 请参阅我的在线注释以获取解释。 本质上,您必须找出GMT从服务器的时间起偏移了几秒(在您的情况下为+3600
秒)。
//The date string
NSString *dStr = @"/Date(1357306469510+0100)/";
//Get the unix time
NSUInteger unixStart = [dStr rangeOfString:@"("].location + 1;
NSUInteger unixEnd = ([dStr rangeOfString:@"+"].location == NSNotFound ? [dStr rangeOfString:@"-"].location : [dStr rangeOfString:@"+"].location);
double unixTime = [[dStr substringWithRange:NSMakeRange(unixStart, unixEnd - unixStart)] doubleValue] / 1000;
NSLog(@"%f", unixTime);
//Get the timezone
NSUInteger tzStart = unixEnd;
NSUInteger tzEnd = [dStr rangeOfString:@")"].location;
float tzOffset = [[dStr substringWithRange:NSMakeRange(tzStart, tzEnd - tzStart)] floatValue] / 100 * 60 * 60;
NSLog(@"%f", tzOffset);
//Calculate the date
NSDate *date = [[NSDate dateWithTimeIntervalSince1970:unixTime] dateByAddingTimeInterval:tzOffset];
NSLog(@"%@", date);
据我所知,Unix时间戳没有时区字段,它以GMT为标准。 如果要将带时区的时间戳转换为本地时间,请增加或减去与GMT相差的秒数。 当您从
NSTimeInterval unixTime = [[jsonDate substringWithRange:NSMakeRange(startPosition, 13)] doubleValue] / 1000;
将3600秒添加到unixTime,
unixTime = unixTime+3600.0;//covering the offset. One hour in your case.
现在显示这次
NSDate *date = [NSDate dateWithTimeIntervalSince1970:unixTime];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.