服务器以2012-04-30T10:00:00(作为字符串)的形式向我发送日期,用于向日历添加条目。我使用以下代码将日期从字符串转换为NSDate,然后用于设置日历事件的开始日期。
2012-04-30T10:00:00和2012-04-30T10:00:00Z的条目将在日历中同时添加。我应该怎么做,如果Z存在,他们会被添加为UTC时间,或者如果没有,他们会被添加为当地时间?
+ (NSDate*) convertDate: (NSString*) fromString
{
[NSTimeZone resetSystemTimeZone];
NSLocale *enUSPOSIXLocale;
NSDateFormatter *sRFC3339DateFormatter = [[NSDateFormatter alloc] init];
enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[sRFC3339DateFormatter setLocale:enUSPOSIXLocale];
[sRFC3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[sRFC3339DateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *date = [sRFC3339DateFormatter dateFromString:fromString];
return date;
}
答案 0 :(得分:0)
将格式化程序的时区设置为UTC。这样就可以了:
[sRFC3339DateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
编辑:如果Z存在,您需要将时区设置为UTC,否则请使用系统时区,如:
+ (NSDate*) convertDate: (NSString*) fromString
{
[NSTimeZone resetSystemTimeZone];
NSLocale *enUSPOSIXLocale;
NSDateFormatter *sRFC3339DateFormatter = [[NSDateFormatter alloc] init];
enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[sRFC3339DateFormatter setLocale:enUSPOSIXLocale];
[sRFC3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
if( [fromString characterAtIndex:[fromString length]-1] == 'Z' ) {
[sRFC3339DateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
}
else {
[sRFC3339DateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
}
NSDate *date = [sRFC3339DateFormatter dateFromString:fromString];
return date;
}