swiftnsdateswift4dateformatter

Get list of months between dates


I have two dates i.e. 2/02/2016 & 19/03/2018

i am trying to fetch months & year between this dates as

output should be

Feb 2016, Mar 2016 ......and so on.... Jan 2018, Feb 2018, Mar 2018.

Tried month Gap code -

  let date1 = DateComponents(calendar: .current, year: 2016, month: 2, day: 2).date!
  let date2 = DateComponents(calendar: .current, year: 2018, month: 3, day: 19).date!
  let monthGap = Calendar.current.dateComponents([.month], from: date1, to: date2)
  print("monthGap is \(String(describing: monthGap.month))")//prints monthGap is 25

Solution

  • Here is a simple method that returns you the date and month in the format as you described above,

    func getMonthAndYearBetween(from start: String, to end: String) -> [String] {
        let format = DateFormatter()
        format.dateFormat = "dd/MM/yyyy"
    
        guard let startDate = format.date(from: start),
            let endDate = format.date(from: end) else {
                return []
        }
    
        let calendar = Calendar(identifier: .gregorian)
        let components = calendar.dateComponents(Set([.month]), from: startDate, to: endDate)
    
        var allDates: [String] = []
        let dateRangeFormatter = DateFormatter()
        dateRangeFormatter.dateFormat = "MMM yyyy"
    
        for i in 0 ... components.month! {
            guard let date = calendar.date(byAdding: .month, value: i, to: startDate) else {
            continue
            }
    
            let formattedDate = dateRangeFormatter.string(from: date)
            allDates += [formattedDate]
        }
        return allDates
    }
    

    And you call it like,

    getMonthAndYearBetween(from: "2/02/2016", to: "19/03/2018")