Joseph Mikko Manoza
Joseph Mikko Manoza

Reputation: 296

FSCalendar: how to get dates in two dates?

I am using Swift 3, and i would like to print the every day between two dates.

For example:

08-10-2017 -> Start Date

08-15-2017 -> End Date

Should print:

08-10-2017

08-11-2017

08-12-2017

08-13-2017

08-14-2017

08-15-2017

I want to get ranges in two specific date, can someone help me out please. I tried to put these two dates to for loop but no chance.

Upvotes: 3

Views: 1669

Answers (1)

dirtydanee
dirtydanee

Reputation: 6151

You need to create a calendar based dates, and start increasing start date until you reach end date. Here is a code snippet, how to do it:

func showRange(between startDate: Date, and endDate: Date) {
    // Make sure startDate is smaller, than endDate
    guard startDate < endDate else { return }

    // Get the current calendar, i think in your case it should some fscalendar instance
    let calendar = Calendar.current
    // Calculate the endDate for your current calendar
    let calendarEndDate = calendar.startOfDay(for: endDate)

    // Lets create a variable, what we can increase day by day
    var currentDate = calendar.startOfDay(for: startDate)

    // Run a loop until we reach the end date
    while(currentDate <= calendarEndDate) {
        // Print the current date
        print(currentDate)
        // Add one day at the time
        currentDate = Calendar.current.date(byAdding: .day, value: 1, to: currentDate)!      
    }
}

Usage:

let today = Date()
let tenDaysLater = Calendar.current.date(byAdding: .day, value: 10, to: today)!
showRange(between: today, and: tenDaysLater)

Upvotes: 3

Related Questions