这个 Objective-C 日期检查方法可以吗?附加代码(得到不同的结果)
我很困惑,因为当两个日期相同的年/月/日/时/分/秒查看我的应用程序时,下面的方法似乎不起作用,但是当我编写单元测试来测试它时似乎工作正常。下面的代码是否由于某种原因不健壮?
代码是:
- (BOOL)isAfterThisDate:(NSDate*)thisDate {
NSComparisonResult result = [self compare:thisDate];
if (result == NSOrderedDescending) {
NSLog(@" - isAfterThisDate: %@ is after %@ is TRUE", [self stringSummary], [thisDate stringSummary]);
return TRUE;
} else {
NSLog(@" - isAfterThisDate: %@ is after %@ is FALSE", [self stringSummary], [thisDate stringSummary]);
return FALSE;
}
}
这是我的应用程序日志的摘录(即当我在应用程序中使用此方法时)。我原以为这是错误的,就像我的单元测试支持一样。
isAfterThisDate: Thu 03-11-2011 09:00:00 GMT+10:00 is after Thu 03-11-2011 09:00:00 GMT+10:00 is TRUE
作为参考,我使用的辅助方法是:
- (NSString*) stringSummary {
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"EEE dd-MM-yyyy HH:mm:ss zzz"];
NSString* str = [formatter stringFromDate:self];
return str;
}
I'm perplexed as I'm not the method below is seemingly NOT working when looking at my application when both dates are the same Year/Month/Date/Hour/Minute/Sec, HOWEVER when I write a unit test to test it it seems to work fine. Is the code below not robust for some reason?
Code is:
- (BOOL)isAfterThisDate:(NSDate*)thisDate {
NSComparisonResult result = [self compare:thisDate];
if (result == NSOrderedDescending) {
NSLog(@" - isAfterThisDate: %@ is after %@ is TRUE", [self stringSummary], [thisDate stringSummary]);
return TRUE;
} else {
NSLog(@" - isAfterThisDate: %@ is after %@ is FALSE", [self stringSummary], [thisDate stringSummary]);
return FALSE;
}
}
Here's an extract from my application log (i.e. when I use this method in my application). I was expecting this to be false like my unit test supports.
isAfterThisDate: Thu 03-11-2011 09:00:00 GMT+10:00 is after Thu 03-11-2011 09:00:00 GMT+10:00 is TRUE
For reference the helper method I used is:
- (NSString*) stringSummary {
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"EEE dd-MM-yyyy HH:mm:ss zzz"];
NSString* str = [formatter stringFromDate:self];
return str;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常最好使用
因此,在这种情况下, -earlierDate: 或 -laterDate: ,如果您只想使用结果日期对象本身,或者您只是测试给定日期,那么是的,-timeIntervalSinceLastDate。
一般来说,格式化程序仅用于生成人类可读的值形式,而不用于对值本身进行操作。
It's generally better to use
So in this case, -earlierDate: or -laterDate: , if you're just going to use the resultant date object itself, or if you're just testing a given date, then yes, -timeIntervalSinceLastDate.
Generally speaking, formatters are only for generating human-readable forms of a value and not for doing operations on the values themselves.
是的
(仅供参考 - 正如凯文指出的 - 我没有欣赏我的约会中出现的亚秒)
Yes
(for reference - as Kevin pointed out - I hadn't appreciated the subseconds which were present in my dates)