iOS 6 dateFromString returns wrong date

2019-07-16 07:32发布

问题:

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?

回答1:

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.


回答2:

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);  


标签: ios6