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 time slots for a particular time difference between two date. We are using swift language and will get array of time slots, between two date and time.

Code to get array of time interval slots

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 time slots function

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. Because in above function the date format used is 12 hour format.

Where to go from here

In this post, we went through a short code block that offers us the ability to get time interval sots for two date objects. We successfully get array of time intervals as per the difference of time needed between two time slots.

Read more articles

1 thought on “Get array of time interval slots between two dates”

Comments are closed.