Swift days between two NSDates

后端 未结 27 1517
清歌不尽
清歌不尽 2020-11-27 13:30

I\'m wondering if there is some new and awesome possibility to get the amount of days between two NSDates in Swift / the \"new\" Cocoa?

E.g. like in Ruby I would do:

27条回答
  •  死守一世寂寞
    2020-11-27 13:57

    All answer is good. But for Localizations we need calculates a number of decimal days in between two dates. so we can provide the sustainable decimal format.

    // This method returns the fractional number of days between to dates
    func getFractionalDaysBetweenDates(date1: Date, date2: Date) -> Double {
    
        let components = Calendar.current.dateComponents([.day, .hour], from: date1, to: date2)
    
        var decimalDays = Double(components.day!)
        decimalDays += Double(components.hour!) / 24.0
    
        return decimalDays
    }
    

提交回复
热议问题