NSDateFormatter time zone abbreviation

2019-07-20 03:09发布

I need to recognize date strings like Tue Aug 13 17:29:20 MSK 2013. And, as I know, to do that I need to use 'V' symbol in NSDateFormmater, but it only recognizes GMT+04:00 like time zones. Is there any other way to parse time zone abbreviation?

Here is the code:

  NSDateFormatter *dft = [[NSDateFormatter alloc] init];
  [dft setDateFormat:@"EEE MMM dd HH:mm:ss V yyyy"];
  NSLog(@"%@", [dft stringFromDate:[NSDate date]]);
  NSLog(@"%@", [dft dateFromString:@"Tue Aug 13 17:29:20 MSK 2013"]);

Output:

Tue Aug 13 17:37:41 GMT+04:00 2013
(null)

With NSLog(@"%@", [dft dateFromString:@"Tue Aug 13 17:29:20 GMT+04.00 2013"]) output is fine.

1条回答
家丑人穷心不美
2楼-- · 2019-07-20 03:33

according to http://www.openradar.me/9944011, Apple updated the ICU library which NSDateFormatter depends on, some time during the Lion/iOS 5 era. and it no longer handles most 3-letter timezones like "MSK" in particular (Moscow Time) because they're ambiguous, they only are used if the "cu" flag is set for the locale.

Which means that you get to handle it. For example with this:

 NSString *threeLetterZone = [[dateString componentsSeparatedByString:@" "] objectAtIndex:4];
 NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:threeLetterZone];
 if (timeZone) 
 {
            NSString *gmtTime = [dateString stringByReplacingOccurrencesOfString:threeLetterZone withString:@"GMT"];
            date = [[pivotalDateFormatter dateFromString:gmtTime] dateByAddingTimeInterval:-timeZone.secondsFromGMT];
 }

Based on this code

查看更多
登录 后发表回答