通过快速计算中午的天数差异

时间:2015-04-04 14:56:11

标签: swift date-difference

我有一个客观的例子,如何计算日期差异作为中间数,在Apple的“日期和时间编程指南”中发布。在Swift中做同样的事情是否可行?

    @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

2 个答案:

答案 0 :(得分:0)

基于Objective-C到Swift转换的基本文档:

extension NSCalendar {
  public func daysApart (sd: NSDate, ed: NSDate) -> Int {
    return ordinalityOfUnit(.DayCalendarUnit, inUnit: .EraCalendarUnit, forDate: ed) -
           ordinalityOfUnit(.DayCalendarUnit, inUnit: .EraCalendarUnit, forDate: sd)
  }
}

答案 1 :(得分:0)

我会做这样的事情:

extension NSCalendar {
    func daysWithinEraFromDate(startDate: NSDate, toDate endDate: NSDate) -> NSInteger {
        let startDay = self.ordinalityOfUnit(.DayCalendarUnit, inUnit: .EraCalendarUnit, forDate: startDate)
        let endDay = self.ordinalityOfUnit(.DayCalendarUnit, inUnit: .EraCalendarUnit, forDate: endDate)
        return endDay - startDay
    }

}