Number of days between two NSDate objects

前端 未结 4 1408
悲&欢浪女
悲&欢浪女 2020-12-16 04:31

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 correct

4条回答
  •  醉梦人生
    2020-12-16 04:55

    I think you are looking for this (from the Date and Time Programming Guide):

    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
    

    EDIT: Swift version:

    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
        }
    }
    

提交回复
热议问题