-3

I have to calculate the time between two NSDates in Month + Year.

Example 1:

Start Date: September 2018
End Date: May 2019 

So I have to get the difference between these two dates and have to display only last 6 months like below:

April 2019
March 2019
February 2019
January 2019
December 2018
November 2018

Example 2:

Start Date: October 2019
End Date: December 2019 

Output should be:

November 2019
October 2019

I can able to to get the difference between two dates in months using below code:

let components = Calendar.current.dateComponents([.weekOfYear, .month], from: subscriptionDate!, to: currentDate!)

Can anyone please help me on this?

Thank you!

Mahendra
  • 8,448
  • 3
  • 33
  • 56
Anand Gautam
  • 2,541
  • 3
  • 34
  • 70

2 Answers2

1

You can do this in following way...

//set start & end date in correct format
let strStartDate = "September 2019"
let strEndDate = "December 2019"

//create date formatter
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"

//convert string into date object
guard let startDate = formatter.date(from: strStartDate) else {
  print("invalid start date")
   return
}

 //convert string into date object
guard let endDate = formatter.date(from: strEndDate) else {
  print("invalid end date time")
  return
}

//calculate the month from end date and that should not exceed the start date
for month in 1...6 {

  if let dt = Calendar.current.date(byAdding: .month, value: -month, to: endDate) {
     if dt.compare(startDate) == .orderedAscending {
        break
      } 
      print(formatter.string(from: dt!))
  }
}
Mahendra
  • 8,448
  • 3
  • 33
  • 56
0

Here's a way to do this:

func monthsBetween(start: DateComponents, end: DateComponents) -> [String] {
    let monthsCount = Calendar.current.dateComponents([.month], from: start, to: end).month! - 1
    guard monthsCount > 0 else { return [] }
    return (1...monthsCount).map {
        var monthYear = start
        monthYear.month! += $0
        let date = Calendar.current.date(from: monthYear)!
        let formatter = DateFormatter()
        formatter.dateFormat = "MMMM yyyy"
        return formatter.string(from: date)
    }
}

You should pass in DateComponents with only the month and year components into this method. You can get a DateComponents object with only the month and year from a Date like this.

Calendar.current.dateComponents([.month, .year], from: someDate)
Sweeper
  • 213,210
  • 22
  • 193
  • 313