How to Get an Array of Days Between Two Dates in Swift

How to get an array of days between two dates in Swift?

You could implement it like this:

func datesRange(from: Date, to: Date) -> [Date] {
// in case of the "from" date is more than "to" date,
// it should returns an empty array:
if from > to { return [Date]() }

var tempDate = from
var array = [tempDate]

while tempDate < to {
tempDate = Calendar.current.date(byAdding: .day, value: 1, to: tempDate)!
array.append(tempDate)
}

return array
}

Usage:

let today = Date()
let nextFiveDays = Calendar.current.date(byAdding: .day, value: 5, to: today)!

let myRange = datesRange(from: today, to: nextFiveDays)
print(myRange)
/*
[2018-03-20 14:46:03 +0000,
2018-03-21 14:46:03 +0000,
2018-03-22 14:46:03 +0000,
2018-03-23 14:46:03 +0000,
2018-03-24 14:46:03 +0000,
2018-03-25 14:46:03 +0000]
*/

All dates between two Date objects (Swift)

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)!
}

Get array of dates between today and given date in Swift?

extension Formatter {
static let date: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter
}()
}

extension Date {
var noon: Date {
return Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
}
}

func dates(for date: String) -> [String] {    
// For calendrical calculations you should use noon time
// So lets get endDate's noon time
guard let endDate = Formatter.date.date(from: date)?.noon else { return [] }
// then lets get today's noon time
var date = Date().noon
var dates: [String] = []
// while date is less than or equal to endDate
while date <= endDate {
// add the formatted date to the array
dates.append( Formatter.date.string(from: date))
// increment the date by one day
date = Calendar.current.date(byAdding: .day, value: 1, to: date)!
}
return dates
}

dates(for: "2019-06-29")  // ["2019-06-25", "2019-06-26", "2019-06-27", "2019-06-28", "2019-06-29"]

A method which returns an array of dates that are in between two dates - Swift 3

You are adding 1 to the same start date so your array is filled with the same date over and over. Simply replace 1 with the loop index + 1.

for i in 0 ... 30 {
if let newDate = cal.date(byAdding: .day, value: i + 1, to: startDate) {
dates.append(newDate)
}
}

And you don't need the start variable.

Array for dates between two dates

// minDate and maxDate represent your date range
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *days = [[NSDateComponents alloc] init];
NSInteger dayCount = 0;
while ( TRUE ) {
[days setDay: ++dayCount];
NSDate *date = [gregorianCalendar dateByAddingComponents: days toDate: minDate options: 0];
if ( [date compare: maxDate] == NSOrderedDescending )
break;
// Do something with date like add it to an array, etc.
}
[days release];
[gregorianCalendar release];

Get the dates of all tuesdays between two dates in Swift

You can use calendar method nextDate(after:, matching:, matchingPolicy, repeatedTimePolicy:, direction:) inside a while loop and add a condition to check if the resulting date is less or equal to the end date:

func nextDate(after date: Date, matching components: DateComponents, matchingPolicy: MatchingPolicy, repeatedTimePolicy: RepeatedTimePolicy = .first, direction: SearchDirection = .forward) -> Date?


var start = DateComponents(calendar: .current, year: 2020, month: 9, day: 21).date!
let end = DateComponents(calendar: .current, year: 2021, month: 2, day: 15).date!

var dates: [Date] = []
while let date = Calendar.current.nextDate(after: start, matching: DateComponents(weekday: 3), matchingPolicy: .strict), date <= end {
dates.append(date)
start = date
}

print(dates)

You can also extend DateInterval and create a custom method to return all dates between start and end dates that matches the date components:

extension DateInterval {
func dates(matching components: DateComponents) -> [Date] {
var start = self.start
var dates: [Date] = []
while let date = Calendar.current.nextDate(after: start, matching: components, matchingPolicy: .strict), date <= end {
dates.append(date)
start = date
}
return dates
}
}

Usage:

let start = DateComponents(calendar: .current, year: 2020, month: 9, day: 21).date!
let end = DateComponents(calendar: .current, year: 2021, month: 2, day: 15).date!
let dateInterval: DateInterval = .init(start: start, end: end)
let tuesdays = dateInterval.dates(matching: .init(weekday: 3))
print(tuesdays)

This will print

[2020-09-22 03:00:00 +0000, 2020-09-29 03:00:00 +0000, 2020-10-06 03:00:00 +0000, 2020-10-13 03:00:00 +0000, 2020-10-20 03:00:00 +0000, 2020-10-27 03:00:00 +0000, 2020-11-03 03:00:00 +0000, 2020-11-10 03:00:00 +0000, 2020-11-17 03:00:00 +0000, 2020-11-24 03:00:00 +0000, 2020-12-01 03:00:00 +0000, 2020-12-08 03:00:00 +0000, 2020-12-15 03:00:00 +0000, 2020-12-22 03:00:00 +0000, 2020-12-29 03:00:00 +0000, 2021-01-05 03:00:00 +0000, 2021-01-12 03:00:00 +0000, 2021-01-19 03:00:00 +0000, 2021-01-26 03:00:00 +0000, 2021-02-02 03:00:00 +0000, 2021-02-09 03:00:00 +0000]

How to get dates for every Friday between two dates?

You just need to add a weekday parameter to your method and check if the weekday of the date inside the loop before adding it to your array:

extension Formatter {
static let date = DateFormatter()
}

func dates(for date: String, weekday: Int? = nil) -> [String] {
Formatter.date.locale = Locale(identifier: "en_US_POSIX")
Formatter.date.dateFormat = "yyyy-MM-dd"
// first get the endDate
guard var endDate = Formatter.date.date(from: date) else { return [] }
// for calendrical calculations you should use noon time
endDate = Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: endDate)!
// lets get todays noon time to start
var date = Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: Date())!
var dates: [String] = []
// while date less than or equal to end date
while date <= endDate {
if weekday == nil {
dates.append(Formatter.date.string(from: date))
date = Calendar.current.date(byAdding: .day, value: 1, to: date)!
} else if let weekday = weekday, Calendar.current.component(.weekday, from: date) == weekday {
// add the formatted date to the array
dates.append(Formatter.date.string(from: date))
date = Calendar.current.date(byAdding: .weekOfYear, value: 1, to: date)!
} else {
date = Calendar.current.date(byAdding: .day, value: 1, to: date)!
}
}
return dates
}

dates(for: "2019-12-25")  // ["2019-10-23", "2019-10-24", "2019-10-25", "2019-10-26", "2019-10-27", "2019-10-28", "2019-10-29", "2019-10-30", "2019-10-31", "2019-11-01", "2019-11-02", "2019-11-03", "2019-11-04", "2019-11-05", "2019-11-06", "2019-11-07", "2019-11-08", "2019-11-09", "2019-11-10", "2019-11-11", "2019-11-12", "2019-11-13", "2019-11-14", "2019-11-15", "2019-11-16", "2019-11-17", "2019-11-18", "2019-11-19", "2019-11-20", "2019-11-21", "2019-11-22", "2019-11-23", "2019-11-24", "2019-11-25", "2019-11-26", "2019-11-27", "2019-11-28", "2019-11-29", "2019-11-30", "2019-12-01", "2019-12-02", "2019-12-03", "2019-12-04", "2019-12-05", "2019-12-06", "2019-12-07", "2019-12-08", "2019-12-09", "2019-12-10", "2019-12-11", "2019-12-12", "2019-12-13", "2019-12-14", "2019-12-15", "2019-12-16", "2019-12-17", "2019-12-18", "2019-12-19", "2019-12-20", "2019-12-21", "2019-12-22", "2019-12-23", "2019-12-24", "2019-12-25"]
dates(for: "2019-12-25", weekday: 6) // ["2019-10-25", "2019-11-01", "2019-11-08", "2019-11-15", "2019-11-22", "2019-11-29", "2019-12-06", "2019-12-13", "2019-12-20"]

func firstDayOfTheMonth(until date: String) -> [String] {
Formatter.date.locale = Locale(identifier: "en_US_POSIX")
Formatter.date.dateFormat = "yyyy-MM-dd"
guard let endDate = Formatter.date.date(from: date) else { return [] }
var date = Date()
var dates: [String] = []
// while date less than or equal to end date
while let firstDayOfTheMonth = Calendar.current.nextDate(after: date, matching: .init(day: 1), matchingPolicy: .nextTime), firstDayOfTheMonth <= endDate {
dates.append(Formatter.date.string(from: firstDayOfTheMonth))
date = firstDayOfTheMonth
}
return dates
}

firstDayOfTheMonth(until: "2019-12-25")  // ["2019-11-01", "2019-12-01"]


Related Topics



Leave a reply



Submit