是否只有我的XCode/computer/iOS设备使用此代码获得零?这太疯狂了!
NSDateFormatter *f = [NSDateFormatter new];
[f setDateFormat:@"yyyy-MM-dd"];
id ret = [f dateFromString:@"2014-10-05"];
NSLog(@"date = %@", ret);
这是我控制台上的日志:
2015-04-06 21:35:22.899测试[665:222261]日期=(空)
BTW:这是一个新项目,我在模拟器和iPhone上都有。
这是一些与localTimeZone有关的错误,请检查以下内容:
NSDateFormatter *f = [NSDateFormatter new];
NSTimeZone *local = [NSTimeZone localTimeZone];
NSLog(@"secondsFromGMT = %ld", [local secondsFromGMT]); // this is -14400
[f setTimeZone:local];
NSDate *ret = [f dateFromString:@"2014-10-05"];
NSLog(@"date = %@", ret); // this is nil
[f setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:-14400]];
[f setDateFormat:@"yyyy-MM-dd"];
ret = [f dateFromString:@"2014-10-05"];
NSLog(@"date = %@", ret); // this is 2014-10-05 04:00:00 +0000
我最终在我的代码中这样做:
NSDateFormatter *f = [NSDateFormatter new];
NSTimeZone *z = [NSTimeZone localTimeZone];
z = [NSTimeZone timeZoneForSecondsFromGMT:z.secondsFromGMT];
[f setTimeZone:z];
// use f here no problem