Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 563
ixany Avatar asked Sep 12 '15 08:09

ixany


2 Answers

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)! } 
like image 83
Martin R Avatar answered Oct 11 '22 22:10

Martin R


Using extension:

extension Date {     static func dates(from fromDate: Date, to toDate: Date) -> [Date] {         var dates: [Date] = []         var date = fromDate                  while date <= toDate {             dates.append(date)             guard let newDate = Calendar.current.date(byAdding: .day, value: 1, to: date) else { break }             date = newDate         }         return dates     } } 

Usage:

let datesBetweenArray = Date.dates(from: Date(), to: Date()) 
like image 30
Alvin George Avatar answered Oct 11 '22 23:10

Alvin George