swiftnsdatensdateformatternscalendarnsdatecomponents

All dates between two Date objects (Swift)


I’m creating a date using NSDateComponents().

let startDate = NSDateComponents()
startDate.year = 2015
startDate.month = 9
startDate.day = 1
let calendar = NSCalendar.currentCalendar()
let startDateNSDate = calendar.dateFromComponents(startDate)!

... now I want to print all dates since the startDate until today, NSDate(). I’ve already tried playing with NSCalendarUnit, but it only outputs the whole difference, not the single dates between.

let unit: NSCalendarUnit = [.Year, .Month, .Day, .Hour, .Minute, .Second]
let diff = NSCalendar.currentCalendar().components(unit, fromDate: startDateNSDate, toDate: NSDate(), options: [])

How can I print all dates between two Dateobjects?

Edit 2019

In the meantime the naming of the classes had changed – NSDate is now just Date. NSDateComponents is now called DateComponents. NSCalendar.currentCalendar() is now just Calendar.current.


Solution

  • Just add one day unit to the date until it reaches the current date (Swift 2 code):

    var date = startDateNSDate // first date
    let endDate = NSDate() // last date
    
    // Formatter for printing the date, adjust it according to your needs:
    let fmt = NSDateFormatter()
    fmt.dateFormat = "dd/MM/yyyy"
    
    // While date <= endDate ...
    while date.compare(endDate) != .OrderedDescending {
        print(fmt.stringFromDate(date))
        // Advance by one day:
        date = calendar.dateByAddingUnit(.Day, value: 1, toDate: date, options: [])!
    }
    

    Update for Swift 3:

    var date = startDate // first date
    let endDate = Date() // last date
    
    // Formatter for printing the date, adjust it according to your needs:
    let fmt = DateFormatter()
    fmt.dateFormat = "dd/MM/yyyy"
    
    while date <= endDate {
        print(fmt.string(from: date))
        date = Calendar.current.date(byAdding: .day, value: 1, to: date)!
    }