【问题标题】:A bug? NSDateFormatter dateFromString Returns null only for this date string [closed]一个错误? NSDateFormatter dateFromString 仅为此日期字符串返回 null [关闭]
【发布时间】:2014-05-23 15:23:57
【问题描述】:
NSString *string = @"1990-04-15";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
return [dateFormatter dateFromString:string];

这总是返回null,当“字符串”被任何其他日期字符串更改时它可以正常工作,这个日期(1990-04-15)有那么特别吗?

xcode 5、IOS 7、iphone 应用

整个方法和上下文:

在“Tools.m”中:

+(NSDate *)stringToDate:(NSString *)string{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
return [dateFormatter dateFromString:string];
}

以及调用的方法:

NSDate *date = [Tools stringToDate:@"1990-04-15"];
NSLog(@"---- the date:%@",date);

【问题讨论】:

  • 当然这是一个特殊的日子……艾玛·沃特森出生于它。
  • 代码很好,当我测试它时返回一个NSDate对象。是否还有其他可能导致问题的东西?
  • 你能把整个方法贴出来吗?以及它的使用范围?因为当前的 sn-p 一切正常
  • 对于所有说它运行良好的人:请包括您的地理位置和运行良好的时区。另外,OP,请同时包括 您的 位置和时区。我在NSDateFormatter 中看到了只影响特定区域的人的错误:对一个人“正常工作”的东西返回nil 对另一个人。有关此示例,请参阅 stackoverflow.com/questions/12167829/…
  • @NSGod 这不是错误!日期格式化程序比您知道的更多。 :) 它与当地夏令时有关(在指定或假定的语言环境中) - 提议的日期时间是在由于提前设置时钟而导致的“缺失时间”期间。

标签: ios nsdateformatter


【解决方案1】:

你在中国吗?如果是这样,那是因为时间转移到了夏令时,所以 1990 年 4 月 15 日午夜不存在——时间直接跳到了凌晨 1:00。 (您没有提供时间,默认时间是午夜。并且您没有提供时区,因此假定您自己的语言环境。)

【讨论】:

  • stackoverflow.com/questions/12167829/… 的答案一模一样:他在巴西,而出事的那天是巴西当年实行夏令时的那一天。
  • 你是天才!!!我google了一会儿,中国就在那天(1990年4月15日......艾玛沃特森出生:))开始实行夏令时,一年后停止了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-07
  • 2013-11-03
相关资源
最近更新 更多