Swift iOS 中两个 NSDate 的月和年差异

Difference between two NSDates in Months and Years in Swift iOS

我必须计算月 + 年中两个 NSDate 之间的时间。

示例 1:

Start Date: September 2018
End Date: May 2019 

所以我必须得到这两个日期之间的差异,并且必须只显示最近 6 个月,如下所示:

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

示例 2:

Start Date: October 2019
End Date: December 2019 

输出应该是:

November 2019
October 2019

我可以使用以下代码获得两个日期之间的月差:

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

谁能帮我解决这个问题?

谢谢!

您可以通过以下方式进行...

//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!))
  }
}

这是一种方法:

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! += [=10=]
        let date = Calendar.current.date(from: monthYear)!
        let formatter = DateFormatter()
        formatter.dateFormat = "MMMM yyyy"
        return formatter.string(from: date)
    }
}

您应该将 DateComponents 仅包含月份和年份组件传递给此方法。你可以像这样从 Date 中得到一个只有月份和年份的 DateComponents 对象。

Calendar.current.dateComponents([.month, .year], from: someDate)