2

我最近升级到 iOS 6,发现 dateFromString 工作不正常,除非我的 dateFormat 有问题。它在升级之前工作。

代码:

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

有什么建议么?

4

2 回答 2

6

看起来格式化程序更改了 iOS 6 中的规格:

  • OS X v10.8 和 iOS 6.0 中的格式化程序使用版本tr35-25
  • iOS 5.0-5.1 中的格式化程序使用版本tr35-19
于 2012-09-24T14:59:51.713 回答
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);  
于 2013-02-13T07:33:48.917 回答