我正在尝试使用RestKit导入数据并将数据映射到CoreData。
以下是API的数据。
active": false,
"date": "2012-09-09",
"desc": "",
"end": "18:30",
"location": "",
"simStatus": "Accepted",
"start": "17:00",
"title": "The title"
当我尝试将这些映射到核心数据时,有时候日期会发生变化。例如,存储在Core Data中的上述数据最终会以start = 1970-1-1 23:00和end = 1970-1-1 00:30结束?
API发送的时间是本地时间,API知道应用程序的使用时间和地点。想想体育赛事,我们知道客场比赛的地点/时间。
我需要将这些时间和日期存储在Core Data中,确切的时间是hh:mm,API将它们交给他们。不确定为什么Core Data或Restkit决定改变它们?我理解1970年的部分作为开始和结束没有日期,但为什么要改变小时?
有谁知道解决方案?
下面是RestKit映射代码,我尝试过timeZone,没有timeZone,本地时区,UTC时区等等...我也尝试过使用和不使用en_US_POSIX。
NSDateFormatter* timeFormatter = [NSDateFormatter new];
[timeFormatter setDateFormat:@"HH:mm"];
timeFormatter.timeZone = [NSTimeZone localTimeZone];
timeFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
NSDateFormatter* dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
dateFormatter.timeZone = [NSTimeZone localTimeZone];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
gameMapping.dateFormatters = [NSArray arrayWithObjects:dateFormatter, timeFormatter, nil ];
[gameMapping mapKeyPath:@"start" toAttribute:@"start"];
[gameMapping mapKeyPath:@"end" toAttribute:@"end"];
.......
答案 0 :(得分:1)
正如Hot Licks在他的评论中指出的那样,所有NSDate
个对象都是UTC,所以这就是你打印出来时所看到的。因为您正在显式解析设备时区中的值,所以当您查看生成的UTC值时,您会看到一个转变。
通常,我强烈建议将内容发送为完整日期&时间值,包括时区偏移量。 (例如,"2012-09-09T18:30:00-05:00"
。)涉及的变量太多,不能明确所有内容。或者至少将时区作为单独的(但仍然是明确的)值传递。
如果您对服务器端没有任何控制权(正如您所说的那样),那么解析值的解决方法就像它们是UTC一样,然后希望这些东西匹配 - 虽然风险和脆弱 - 听起来它可能是你得到的最佳选择。