Swift days between two NSDates

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

    I translated my Objective-C answer

    let start = "2010-09-01"
    let end = "2010-09-05"
    
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    
    let startDate:NSDate = dateFormatter.dateFromString(start)
    let endDate:NSDate = dateFormatter.dateFromString(end)
    
    let cal = NSCalendar.currentCalendar()
    
    
    let unit:NSCalendarUnit = .Day
    
    let components = cal.components(unit, fromDate: startDate, toDate: endDate, options: nil)
    
    
    println(components)
    

    result

    <NSDateComponents: 0x10280a8a0>
         Day: 4
    

    The hardest part was that the autocompletion insists fromDate and toDate would be NSDate?, but indeed they must be NSDate! as shown in the reference.

    I don't see how a good solution with an operator would look like, as you want to specify the unit differently in each case. You could return the time interval, but than won't you gain much.

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

    The things built into swift are still very basic. As they should be at this early stage. But you can add your own stuff with the risk that comes with overloading operators and global domain functions. They will be local to your module though.

    let now = NSDate()
    let seventies = NSDate(timeIntervalSince1970: 0)
    
    // Standard solution still works
    let days = NSCalendar.currentCalendar().components(.CalendarUnitDay, 
               fromDate: seventies, toDate: now, options: nil).day
    
    // Flashy swift... maybe...
    func -(lhs:NSDate, rhs:NSDate) -> DateRange {
        return DateRange(startDate: rhs, endDate: lhs)
    }
    
    class DateRange {
        let startDate:NSDate
        let endDate:NSDate
        var calendar = NSCalendar.currentCalendar()
        var days: Int {
            return calendar.components(.CalendarUnitDay, 
                   fromDate: startDate, toDate: endDate, options: nil).day
        }
        var months: Int {
            return calendar.components(.CalendarUnitMonth, 
                   fromDate: startDate, toDate: endDate, options: nil).month
        }
        init(startDate:NSDate, endDate:NSDate) {
            self.startDate = startDate
            self.endDate = endDate
        }
    }
    
    // Now you can do this...
    (now - seventies).months
    (now - seventies).days
    
    0 讨论(0)
  • 2020-11-27 13:34

    Swift 3 - Days from today until date

    func daysUntilDate(endDateComponents: DateComponents) -> Int
        {
            let cal = Calendar.current
            var components = cal.dateComponents([.era, .year, .month, .day], from: NSDate() as Date)
            let today = cal.date(from: components)
            let otherDate = cal.date(from: endDateComponents)
    
            components = cal.dateComponents([Calendar.Component.day], from: (today! as Date), to: otherDate!)
            return components.day!
        }
    

    Call function like this

    // Days from today until date
       var examnDate = DateComponents()
       examnDate.year = 2016
       examnDate.month = 12
       examnDate.day = 15
       let daysCount = daysUntilDate(endDateComponents: examnDate)
    
    0 讨论(0)
  • 2020-11-27 13:39

    I'm going to add my version even though this thread is a year old. My code looks like this:

        var name = txtName.stringValue // Get the users name
    
        // Get the date components from the window controls
        var dateComponents = NSDateComponents()
        dateComponents.day = txtDOBDay.integerValue
        dateComponents.month = txtDOBMonth.integerValue
        dateComponents.year = txtDOBYear.integerValue
    
        // Make a Gregorian calendar
        let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
    
        // Get the two dates we need
        var birthdate = calendar?.dateFromComponents(dateComponents)
        let currentDate = NSDate()
    
        var durationDateComponents = calendar?.components(NSCalendarUnit.CalendarUnitDay, fromDate: birthdate!, toDate: currentDate, options: nil)
    
        let numberOfDaysAlive = durationDateComponents?.day
    
        println("\(numberOfDaysAlive!)")
    
        txtGreeting.stringValue = "Hello \(name), You have been alive for \(numberOfDaysAlive!) days."
    

    I hope it helps someone.

    Cheers,

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

    Erin's method updated to Swift 3, This shows days from today (disregarding time of day)

    func daysBetweenDates( endDate: Date) -> Int 
        let calendar: Calendar = Calendar.current 
        let date1 = calendar.startOfDay(for: Date()) 
        let date2 = calendar.startOfDay(for: secondDate) 
        return calendar.dateComponents([.day], from: date1, to: date2).day! 
    }
    
    0 讨论(0)
  • 2020-11-27 13:40

    Here is the answer for Swift 3 (tested for IOS 10 Beta)

    func daysBetweenDates(startDate: Date, endDate: Date) -> Int
    {
        let calendar = Calendar.current
        let components = calendar.components([.day], from: startDate, to: endDate, options: [])
        return components.day!
    }
    

    Then you can call it like this

    let pickedDate: Date = sender.date
    let NumOfDays: Int = daysBetweenDates(startDate: pickedDate, endDate: Date())
        print("Num of Days: \(NumOfDays)")
    
    0 讨论(0)
提交回复
热议问题