1

我很难将日期从字符串转换为以下格式的 NSDate:

2012-09-05 12:00 GMT-5 +DST

到目前为止,我有这个代码:

NSString *myDateStr = @"2012-09-05 12:00 GMT-5 +DST";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-DD HH:mm:ss Z"];
NSDate *date = [formatter dateFromString:myDateStr];

我无法控制日期字符串的格式,因为它来自 API。

我可能需要编写一个自定义格式化程序来解析这个吗?

4

1 回答 1

0

Pass your date string to this function, which would return NSDate object.

You can recheck if you are getting the correct value as GMT-5 +DST is same as CDT. Reference

Setting the timeZone as CDT would give you the same result.

-(NSDate *)timeConvert:(NSString *)string
{
      NSString *firstString = [string substringToIndex:16];
      NSString *lastString = [string substringFromIndex:17];

      NSLog(@"%@, %@", firstString, lastString);
      NSTimeZone *timeZone = [NSTimeZone  timeZoneWithName:lastString];
      NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
      [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
      [formatter setTimeZone: timeZone];

      NSDate *date = [formatter dateFromString:firstString];

      return date;
}
于 2012-09-06T11:28:25.793 回答