2012-09-24 58 views
2

我最近升级到iOS 6,并注意到dateFromString不能正常工作,除非我用我的dateFormat做错了什么。它在升级之前正在工作。iOS 6 dateFromString返回错误的日期

代码:

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

输出:

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

有什么建议?

+0

你找到解决办法吗?我面临同样的问题 –

回答

6

貌似格式化的iOS 6中改变规格:在OS X v10.8和iOS 6.0版本使用tr35-25

  • 格式化程序。
  • iOS 5.0-5.1中的格式化程序使用版本tr35-19
+1

任何官方文档? –

+0

@mihirmehta - 是的。参见[这里](http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html)。 –

+0

谢谢Matt ... –

3

请检查:

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

什么是sourceDate? –