0

我有两个日期,即2/02/201619/03/2018

我正在尝试获取此日期之间的月份和年份

输出应该是

2016 年 2 月,2016 年 3 月......等等...... 2018 年 1 月,2018 年 2 月,2018 年 3 月。

尝试了一个月的差距代码 -

  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
4

2 回答 2

7

这是一个简单的方法,它以上述格式返回日期和月份,

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
}

你这样称呼它,

getMonthAndYearBetween(from: "2/02/2016", to: "19/03/2018")
于 2018-03-19T11:16:01.177 回答
3

斯威夫特 5

根据 Sandeep 的回答,此函数将Date对象作为输入,并返回一个对象数组Date

extension Date {
    
    static func getMonthAndYearBetween(from start: Date, to end: Date) -> [Date] {
        var allDates: [Date] = []
        guard start < end else { return allDates }
        
        let calendar = Calendar.current
        let month = calendar.dateComponents([.month], from: start, to: end).month ?? 0
        
        for i in 0...month {
            if let date = calendar.date(byAdding: .month, value: i, to: start) {
                allDates.append(date)
            }
        }
        return allDates
    }
    
}
于 2020-11-03T12:36:56.233 回答