【发布时间】:2016-12-09 09:49:29
【问题描述】:
我想比较 2 个特定的日子,但是,我想比较月份和年份,而不是天数。例如,我得到了一个日期,比如 2016-08-16,而另一个日期是 2016-08-10,我需要比较日期并得到相等,因为它们的月份是相等的。
因此,我需要一种方法使两个 NSDate 的天数相等,因此我需要将 2016-08-10 设置为 2016-08-00。之后我也可以修改第二个日期并进行比较。
我有简单的相等性代码剪辑器,但我想它也考虑天数和小时数等:
if ([dateOld compare:dateNew] == NSOrderedDescending) {
NSLog(@"date1 is later than date2");
} else if ([dateOld compare:dateNew] == NSOrderedAscending) {
NSLog(@"date1 is earlier than date2");
} else {
NSLog(@"dates are the same");
}
为了使其工作,我需要将 NSDates 的天数和时间“归零”。有什么办法吗?
【问题讨论】:
-
NSDateComponents类参考:developer.apple.com/library/mac/documentation/Cocoa/Reference/… -
NSDateComponents,还有NSCalendar,compareDate:toDate:toUnitGranularity:方法可能就是你要找的。span> -
@Larme 你能举个例子吗?
-
我认为使用我给出的关键词(类名、方法名)和“比较”进行快速搜索应该会给你这样一个快速示例:stackoverflow.com/questions/1854890/…
-
@Larme 好的,谢谢。
标签: ios objective-c nsdate