获取日期之间的月份列表

时间:2018-03-19 11:03:22

标签: swift nsdate swift4 dateformatter

我有两个日期,即 2/02/2016 &的 19/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

2 个答案:

答案 0 :(得分:2)

这是一个简单的方法,它按照您上面描述的格式返回日期和月份,

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")

答案 1 :(得分:0)

快捷键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
    }
    
}