两个NSDate对象之间的天数 [英] Number of days between two NSDate objects
问题描述
我正在尝试比较两天的NSDate对象,我在第一次使用NSDateComponents来计算我的两个日期对象之间的差异,但它工作正常。
I'm trying to compare two days of NSDate objects, I used at the first time NSDateComponents to calculate difference between my two dates Objects, but it is working correctly.
NSString *dateStr =@"2012-11-05 15:00:00";
NSDate *date = [dateFormat dateFromString:dateStr];
NSDateComponents *datesDiff = [calendar components: NSDayCalendarUnit
fromDate: date
toDate: [NSDate date]
options: 0];
这不能解决我的问题。实际上,当date1 = 2012-11-05 23:00:00和date2 = 2012-11-06 10:00:00时,拖曳日期之间的差异是0天和11小时。
我正在寻找能让我发现日期变化的东西,换句话说,当date1 = 2012-11-05 23:00:00和date2 = 2012-11-06 00:01:00时,有一天差异。
That does not resolve my problem. Indeed when date1 = 2012-11-05 23:00:00 and date2 = 2012-11-06 10:00:00, the difference between the tow dates is 0 day and 11 hours. I am looking for something that allows me to detect day changes, in other words when date1 = 2012-11-05 23:00:00 and date2 = 2012-11-06 00:01:00, there's one day diffrence.
如果有人知道解决方案,我会欢迎他的建议。
提前致谢
If someone knows the solution for that, i would welcome his suggestion. Thanks in advance
推荐答案
我认为你正在寻找这个(来自日期和时间编程指南):
I think you are looking for this (from the Date and Time Programming Guide):
清单13两个日期之间的天数,作为中间夜数
Listing 13 Days between two dates, as the number of midnights between
@implementation NSCalendar (MySpecialCalculations)
-(NSInteger)daysWithinEraFromDate:(NSDate *) startDate toDate:(NSDate *) endDate
{
NSInteger startDay=[self ordinalityOfUnit:NSDayCalendarUnit
inUnit: NSEraCalendarUnit forDate:startDate];
NSInteger endDay=[self ordinalityOfUnit:NSDayCalendarUnit
inUnit: NSEraCalendarUnit forDate:endDate];
return endDay-startDay;
}
@end
编辑:Swift版本:
extension NSCalendar {
func daysWithinEraFromDate(startDate: NSDate, endDate: NSDate) -> Int {
let startDay = self.ordinalityOfUnit(.Day, inUnit: NSCalendarUnit.Era, forDate: startDate)
let endDay = self.ordinalityOfUnit(.Day, inUnit: NSCalendarUnit.Era, forDate: endDate)
return endDay - startDay
}
}
这篇关于两个NSDate对象之间的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!