在 Xcode 4 之前,我曾经使用 NSDate initFromString ,但它现在已被弃用,并在 Xcode 4.2 中产生错误。因此,我跳到使用 NSDateFormatter dateFromString ,但在我调用的方法中遇到了问题,该方法从字符串获取日出日期并从字符串获取日落日期以确定是白天还是晚上(所以相同的方法)。第一个调用工作正常,但第二个调用返回 nil。我决定看看它是否可重复,因此我创建了以下简单方法并将其转储到另一个项目中无害的地方:
- (void)testDateFormatter
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat: @"yyyy-MM-dd hh:mm:ss Z"];
NSString *srDateTimeString = @"2011-11-09 07:08:00 -0800";
NSString *ssDateTimeString = @"2011-11-09 17:08:00 -0800";
NSDate *sunriseDateTime = [formatter dateFromString: srDateTimeString];
NSDate *sunsetDateTime = [formatter dateFromString: ssDateTimeString];
return;
}
第一次调用返回正确的日期。第二次调用返回 nil。我尝试了几种变体(例如创建两个单独的 NSDateFormatter、预初始化日期、将日期预初始化为当前时间,然后重新分配),但没有一个达到预期效果。
有谁知道这是怎么回事?由于我在任何地方都没有找到任何对此错误的引用,因此我将其提交给 Apple(错误#10420498)。
杰克
Before Xcode 4 I used to use NSDate initFromString
but it is now deprecated and produces errors in Xcode 4.2. So I jumped over to using NSDateFormatter dateFromString
but ran into an issue in a method I call that gets a sunrise date from string and a sunset date from string to determine if it is day or night (so same method). The first call works fine, but the second call returns nil. I decided to see if it was repeatable so I created the following simple method and dumped it into another project in an innocuous place:
- (void)testDateFormatter
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat: @"yyyy-MM-dd hh:mm:ss Z"];
NSString *srDateTimeString = @"2011-11-09 07:08:00 -0800";
NSString *ssDateTimeString = @"2011-11-09 17:08:00 -0800";
NSDate *sunriseDateTime = [formatter dateFromString: srDateTimeString];
NSDate *sunsetDateTime = [formatter dateFromString: ssDateTimeString];
return;
}
The first call returns the correct date. The second call returns nil. I have tried several variations (such as creating two separate NSDateFormatters, preinitializing the dates, preinitializing the dates to the current time and then reassigning) but none do the expected thing.
Does anyone know what is going on here? Since I hadn't found any reference to this error anywhere I submitted it to Apple (bug #10420498).
Jack
发布评论
评论(1)
在第二个字符串中,小时为 17(24 小时格式),但格式字符串使用
hh
(小写),适用于 12 小时格式。将格式字符串更改为
yyyy-MM-dd HH:mm:ss Z
。在文档中,请参阅 日期格式化程序,其中包含指向 Unicode 日期格式模式 列出每个格式说明符。
In the second string, the hour is 17 (24-hour format) but the format string uses
hh
(lowercase) which is for 12-hour format.Change the format string to
yyyy-MM-dd HH:mm:ss Z
.In the documentation, see Date Formatters which contains a link to the Unicode Date Format Patterns listing each format specifier.