NSDateFormatter time zone abbreviation

隐身守侯 提交于 2020-01-04 14:09:07

问题


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:


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



来源:https://stackoverflow.com/questions/18210707/nsdateformatter-time-zone-abbreviation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!