I would point out that the question should be edited to indicate that you wished to know how to list out the months, since the calculation of an integer denoting the inclusive number of months between 2 dates may be a completely different task. And for that, sweeper's answer should already be considered more than adequate.
I will attempt to give a solution in response to the comment where you clarify that you want a list of the months.
import UIKit
func makeDate(year: Int, month: Int, day: Int) -> Date {
let calendar = Calendar(identifier: .gregorian)
let components = DateComponents(year: year, month: month, day: day) //, hour: hr, minute: min, second: sec)
return calendar.date(from: components)!
}
let date1 = makeDate(year: 2016, month: 10, day: 23) // 23 OCT 2016
let date2 = makeDate(year: 2020, month: 7, day: 10) // 10 JULY 2020
func printMonths(date1: Date, date2: Date) {
guard date1 < date2 else {return}
let month1 = Calendar.current.component(.month, from: date1)
let month2 = Calendar.current.component(.month, from: date2)
let year1 = Calendar.current.component(.year, from: date1)
let year2 = Calendar.current.component(.year, from: date2)
if year1 == year2 {
for month in month1...month2 {
print(DateFormatter().monthSymbols[month - 1])
}
} else {
for year in year1...year2 {
print(year)
switch year {
case year1:
for month in month1...12 {
print(" \(DateFormatter().monthSymbols[month - 1])")
}
case year2:
for month in 1...month2 {
print(" \(DateFormatter().monthSymbols[month - 1])")
}
default:
for month in 1...12 {
print(" \(DateFormatter().monthSymbols[month - 1])")
}
}
print()
}
}
}
printMonths(date1: date1, date2: date2)
This function will print out the month names in order from date1 to date2, printing the years for the months if the 2 dates have different years.
It can easily be modified to print the total number of months by just using a counter each time a month name is printed out, if you wanted that too.
Output from example dates:
2016
October
November
December
2017
January
February
March
April
May
June
July
August
September
October
November
December
2018
January
February
March
April
May
June
July
August
September
October
November
December
2019
January
February
March
April
May
June
July
August
September
October
November
December
2020
January
February
March
April
May
June
July