1

我有一个 .NET REST 服务,它以 JSON 格式返回数据。一个字段是 UTC 中的日期时间,如下所示:

"Synced":"2012-07-11T13:28:42.967"

我想在我的 iOS 应用程序中获取这个日期,但每次我尝试都会得到 null:

NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter  setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSArray *dateFormatters = [[NSArray alloc]initWithObjects:dateFormatter, nil];
[RKObjectMapping setDefaultDateFormatters:dateFormatters];

我做错了什么?谢谢!

4

3 回答 3

5

日期格式为:yyyy-MM-dd'T'HH:mm:ss.SSS

[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
于 2012-07-12T09:07:37.977 回答
3

For future peeps with related RestKit/NSDate issues:

Note that if the RESTful api you are calling is returning a date format with .SSS (e.g. milliseconds) appended to the end, RestKit will not correctly support this format out of the box. The issue is that RestKit does not recognize the date as a standard date format.

In my setup, this did not result in explicit errors; it just meant that RestKit interpreted times in the wrong time zone. For iOS date formatters to work correctly, NSDates must be stored in UTC, but RestKit was converting all dates with the format @"yyyy-MM-dd'T'HH:mm:ss.SSS" into the local timezone, rather than UTC.

To correct this, I added the date formatter from harakiri to RestKit's default date formatters.

Here is the code, applied during RestKit setup. Hopefully this helps someone down the line:

//Add .SSS dateformatter to default formatters:
NSDateFormatter* restKitDates = [NSDateFormatter new];
[restKitDates setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
[restKitDates setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[RKObjectMapping addDefaultDateFormatter:restKitDates];
于 2012-10-21T17:22:11.223 回答
2

尝试这个:

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
 [dateFormatter  setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
 dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
 NSString *str = @"2012-07-11T13:28:42.967";
 //NSArray *dateFormatters = [[NSArray alloc]initWithObjects:dateFormatter, nil];
 NSDate *date = [dateFormatter dateFromString:str];
于 2012-07-12T09:09:37.277 回答