iOS 6 dateFromString returns wrong date

2019-07-16 07:26发布

I recently upgraded to iOS 6 and have noticed dateFromString is not working correctly, unless I'm doing something wrong with my dateFormat. It was working prior to the upgrade.

Code:

NSString *string = @"2012-09-24 - Sun";
NSLog(@"string = %@", string);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en-US"];
[df setLocale:locale];
[df setDateFormat:@"yyyy-MM-dd - EEE"];
NSDate *date = [df dateFromString:string];
NSLog(@"date = %@", date);

Output:

string = 2012-09-24 - Sun
date = 1999-12-26 05:00:00 +0000

Any suggestions?

标签: ios6
2条回答
甜甜的少女心
2楼-- · 2019-07-16 07:51

Looks like the formatters changed specs in iOS 6:

  • Formatters in OS X v10.8 and iOS 6.0 use version tr35-25.
  • Formatters in iOS 5.0-5.1 use version tr35-19.
查看更多
姐就是有狂的资本
3楼-- · 2019-07-16 08:09

Please check this:

NSString *string = @"2012-09-24 - Sun";
NSLog(@"string = %@", string);
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd - EEE"];
NSDate * date = [df dateFromString: string];
NSDate * sourceDate = date;
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;   
date = [[NSDate alloc] initWithTimeInterval:interval sinceDate:date];
NSLog(@"date = %@", date);  
查看更多
登录 后发表回答