ios6 dateFromString返回错误日期。

时间:2022-10-21 18:32:15

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.

我最近升级到ios6,并且注意到dateFromString没有正常工作,除非我的dateFormat有问题。它是在升级之前工作的。

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?

有什么建议吗?

2 个解决方案

#1


6  

Looks like the formatters changed specs in iOS 6:

在iOS 6中,看起来格式化程序改变了规格:

  • Formatters in OS X v10.8 and iOS 6.0 use version tr35-25.
  • 在OS X v10.8和ios6.0中格式化程序使用版本tr35-25。
  • Formatters in iOS 5.0-5.1 use version tr35-19.
  • 在ios5.0 -5.1版本中使用版本tr35-19。

#2


3  

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

#1


6  

Looks like the formatters changed specs in iOS 6:

在iOS 6中,看起来格式化程序改变了规格:

  • Formatters in OS X v10.8 and iOS 6.0 use version tr35-25.
  • 在OS X v10.8和ios6.0中格式化程序使用版本tr35-25。
  • Formatters in iOS 5.0-5.1 use version tr35-19.
  • 在ios5.0 -5.1版本中使用版本tr35-19。

#2


3  

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