2

我从 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 AM GMT,但我应该得到 2012-12-07 09:10:39(大约)。

我怎样才能做到这一点?请帮忙。

4

2 回答 2

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

于 2014-12-27T20:33:02.537 回答
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;
于 2014-11-05T13:16:17.510 回答