Search code examples
iosswiftnsdate

How can i get hours between time's and print each interval?


I would like to get a number of hours between two times as strings formatted as:

startTime = "9:00AM"
endTime = "11:00AM"

and then print each 1-hour interval between them. So for this example, it would be:

9:00 AM - 10:00 AM
10:00 AM - 11:00 AM

another example would be:

startTime = 2:30AM
endTime = 1:30AM

The intervals between that would be from 2:30 AM, 3:30 AM, 4:30 AM etc all the way to 1:30 AM the next day. What is the quickest way this can be done?


Solution

    • Convert the strings to Date objects with DateFormatter and add current day, month, and year to get a reliable date.
    • Use Calendar's method enumerateDates(startingAfter:matching:matchingPolicy: repeatedTimePolicy to get the intermediate dates.
    • With DateComponentsFormatter you can get the string interval representation of two dates.