我从WCF Rest服务获取一些UTC日期字符串,格式如下:
/Date(1354851639500+0530)/
我使用以下代码转换日期:
//jsonDateString = 1354851639500+0530
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; //get number of seconds to add or subtract according to the client default time zone
NSTimeInterval unixTime = [[jsonDateString substringWithRange:NSMakeRange(0, 13)] doubleValue] / 1000; //WCF will send 13 digit-long value for the time interval since 1970 (millisecond precision) whereas iOS works with 10 digit-long values (second precision), hence the divide by 1000
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss a ZZZZ"];
NSString *stringFromDAte = [dateFormatter stringFromDate:[[NSDate dateWithTimeIntervalSince1970:unixTime] dateByAddingTimeInterval:offset]];
NSLog(@"Server GMT: %@", stringFromDAte);
NSDate *currentDadte = [dateFormatter dateFromString:stringFromDAte];
NSTimeInterval interval = [currentDadte timeIntervalSinceDate:[NSDate date]];
return [self dailyLanguage:interval];
但是当我转换时间不正确时。我需要获得接收时间的UTC时间。但我得到的时间值没有偏移值。
例如:如果josnDate = 1354851639500 + 0530, 我正在接受,2012-12-07 03:40:39 GMT,但我应该得到2012-12-07 09:10:39(大约)。
我该怎么做?请帮忙。
答案 0 :(得分:1)
试用此代码
- (NSDate *)deserializeJsonDateString: (NSString *)jsonDateString
{
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; //get number of seconds to add or subtract according to the client default time zone
NSInteger startPosition = [jsonDateString rangeOfString:@"("].location + 1; //start of the date value
NSTimeInterval unixTime = [[jsonDateString substringWithRange:NSMakeRange(startPosition, 13)] doubleValue] / 1000; //WCF will send 13 digit-long value for the time interval since 1970 (millisecond precision) whereas iOS works with 10 digit-long values (second precision), hence the divide by 1000
[[NSDate dateWithTimeIntervalSince1970:unixTime] dateByAddingTimeInterval:offset];
return date;
}
有关详细解答,请点击此链接 http://goo.gl/lE6ut
答案 1 :(得分:0)
你可以试试这个
NSString *jsonDateString = [SingleResponseObject objectForKey:@"datetime"];;
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
NSTimeInterval unixTime = [[jsonDateString substringWithRange:NSMakeRange(0, 13)] doubleValue] / 1000;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss a ZZZZ"];
NSString *stringFromDAte = [dateFormatter stringFromDate:[[NSDate dateWithTimeIntervalSince1970:unixTime] dateByAddingTimeInterval:offset]];
cell.date.text = stringFromDAte;