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 Date
objects?
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
.
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)! }
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With