如何从iOS中的JSON解析Unix时间戳?
我从一些RESTful服务时间戳这种格式:如何从iOS中的JSON解析Unix时间戳?
"/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)。
有人可以提供一个完整的解决方案,或告诉我在哪里可以找到它?
在此先感谢
以下代码应该可以工作。请参阅我的在线评论以获取解释。从本质上讲,你必须弄清楚格林尼治标准时间后多少秒,你的服务器时间被抵消了(在你的情况下,+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);
感谢您的回应。如果我登录从代码中得到的'NSDate',会显示'2015-02-09 07:52:25 + 0000',而记录'[NSDate date]'打印'2015-02-09 06:52: 25 + 0000' ...我需要得到'2015-02-09 07:52:25 + 0100'或'2015-02-09 06:52:25 + 0000' – AppsDev 2015-02-09 06:57:55
@AppsDev你确定你输入的日期是正确的?我测试了它,它似乎为我工作...我用这个网站,得到了unix时间戳,并将其放入字符串:http://www.epochconverter.com/ – rebello95 2015-02-09 07:06:04
它看起来像行为是正确的.. 。如果我添加时区的偏移量,我可以得到毫秒的总数,但我并不是在告诉NSDate这个毫秒值是+1时区,它认为是+0时区...所以我应该用某种方式如果我提供时区与JSON的偏移量,或者让'NSDate'的时区保持为+0并且不提供时区与JSON的偏移量,那么它的时区为+1的'NSDate' – AppsDev 2015-02-09 07:32:16
据我所知,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];
你想显示的时区或没有? – 2015-02-08 17:49:43
@FawadMasud我需要考虑时区在'NSDate'对象中有正确的时间 – AppsDev 2015-02-09 06:33:17