Swift days between two NSDates

后端 未结 27 1207
清歌不尽
清歌不尽 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:49

    2017 version, copy and paste

    func simpleIndex(ofDate: Date) -> Int {
        
        // index here just means today 0, yesterday -1, tomorrow 1 etc.
        
        let c = Calendar.current
        let todayRightNow = Date()
        
        let d = c.date(bySetting: .hour, value: 13, of: ofDate)
        let t = c.date(bySetting: .hour, value: 13, of: todayRightNow)
        
        if d == nil || today == nil {
        
            print("weird problem simpleIndex#ofDate")
            return 0
        }
        
        let r = c.dateComponents([.day], from: today!, to: d!)
        // yesterday is negative one, tomorrow is one
        
        if let o = r.value(for: .day) {
            
            return o
        }
        else {
        
            print("another weird problem simpleIndex#ofDate")
            return 0
        }
    }
    
    0 讨论(0)
  • 2020-11-27 13:51
    let calendar = NSCalendar.currentCalendar();
    let component1 = calendar.component(.Day, fromDate: fromDate)
    let component2 = calendar.component(.Day, fromDate: toDate)
    let difference  = component1 - component2
    
    0 讨论(0)
  • 2020-11-27 13:52

    You could use the following extension:

    public extension Date {
        func daysTo(_ date: Date) -> Int? {
            let calendar = Calendar.current
    
            // Replace the hour (time) of both dates with 00:00
            let date1 = calendar.startOfDay(for: self)
            let date2 = calendar.startOfDay(for: date)
    
            let components = calendar.dateComponents([.day], from: date1, to: date2)
            return components.day  // This will return the number of day(s) between dates
        }
    }
    

    Then, you can call it like this:

    startDate.daysTo(endDate)
    
    0 讨论(0)
  • 2020-11-27 13:53

    I see a couple Swift3 answers so I'll add my own:

    public static func daysBetween(start: Date, end: Date) -> Int {
       Calendar.current.dateComponents([.day], from: start, to: end).day!
    }
    

    The naming feels more Swifty, it's one line, and using the latest dateComponents() method.

    0 讨论(0)
  • 2020-11-27 13:57

    There's hardly any Swift-specific standard library yet; just the lean basic numeric, string, and collection types.

    It's perfectly possible to define such shorthands using extensions, but as far as the actual out-of-the-box APIs goes, there is no "new" Cocoa; Swift just maps directly to the same old verbose Cocoa APIs as they already exist.

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
提交回复
热议问题