Get array of time interval slots between two dates

Get array of time interval slots between two dates


In this post we will learn, how to get array of slots for a particular interval of date time. For this post, we are using swift and will get array of time slots, between two date and time.

Code for getting array of time interval

func getMinutesTimeSlotsBetween(startDateTime:Date, _ endDateTime:Date, andSlotInterval interval:Int) -> [String]{
        var timeSlots: [String] = []
        let formatter = DateFormatter()
        formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
        formatter.dateFormat = "hh:mm a"
           
        var i = 1
        while true {
            let date = startDateTime.addingTimeInterval(TimeInterval(i*interval*60))
            let string = formatter.string(from: date)
            
            if date >= endDateTime {
                break }
            i += 1
            timeSlots.append(string)
        }
        timeSlots array
    }

Understanding parameters of function getMinutesTimeSlotsBetween

startDateTime: accepts a date object.
endDateTime: accepts a date object
interval: time interval example 10, 15, 30 minutes

In order to get time interval slots, you need to pass start date and end date with time in 12 hour format. As in above function the date format used is 12 hour format.