我在使用带有 NSDateFormatter
的自定义日期格式化程序将字符串转换为日期时遇到问题。下面是一个简短的示例,它根据今天的日期创建一个字符串,但无法将其转换回 NSDate
:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"Mdyyyy"];
NSString *example = [dateFormatter stringFromDate:now]; // e.g., 10292013
NSDate *reverse = [dateFormatter dateFromString:example]; // nil?
基本上看来,NSDateFormatter
正在创建一个日期字符串,它本身无法使用与创建该字符串相同的格式将其转回为NSDate
。
使用 MMddyyyy
作为日期字符串是有效的,尽管我无法从 documentation 中看到(方便地仅适用于 iOS 6.0)为什么它很重要:
month M 1..2 09 Month - Use one or two for the numerical month, ....
...
day d 1..2 1 Date - Day of the month
我尝试使用 Mdyyyy
而不是 MMddyyyy
的原因是它更接近于 NSDateFormatterShortStyle
返回的当前 >NSLocale
(M/d/yy
)。
也许有人可能在这里有一些见解,因为我做错了什么,或者我对它应该如何工作的理解是错误的。 (我知道这里有很多关于 NSDateFormatter
的问题,但我没有找到适合我的问题的问题。)
最佳答案
Mdyyyy 作为字符串 -> 日期映射是不明确的。人们无法判断“1112013”是 Jan 11 还是 11 月 1 日。因此 NSDateFormatter 不允许将其用于字符串 ->date。
关于ios - NSDateFormatter:stringFromDate 和 dateFromString 不可逆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19664432/