我有创建日期的功能...

func date(withYear year: Int, month: Int, day: Int) -> Date {
    let components = DateComponents(calendar: Calendar.current, timeZone: nil, era: nil, year: year, month: month, day: day, hour: 0, minute: 0, second: 0, nanosecond: 0, weekday: nil, weekdayOrdinal: nil, quarter: nil, weekOfMonth: nil, weekOfYear: nil, yearForWeekOfYear: nil)
    return components.date!
}


只需要日,月和年为方便。

因此,我创建了两个日期。

let startDate = date(withYear: 2016, month: 9, day: 30) // prints to console as 2016-09-29 23:00:00 +0000
let endDate = date(withYear: 2016, month: 11, day: 1)   // prints to console as 2016-11-01 00:00:00 +0000


然后计算它们之间的月数...

let components = Calendar.current.dateComponents([.month], from: startDate, to: endDate)

print(components.month) // returns 1


这不是2吗?如何计算月份组成部分?是几天数除以30还是什么?如果是这样,我将需要一种新的方法来计算月数。

最佳答案

我有同样的问题,但是NSCalendar可以正常工作,此代码示例证明了这一点。

    let date = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components([.Day , .Month , .Year], fromDate: date)

    let twoMonthdate = calendar.dateByAddingUnit(.Month, value: 2, toDate:date, options: [])

    let difference = calendar.components([.Month], fromDate: date, toDate: twoMonthdate!, options: [])
    //differences is 2 monthses


您的情况是1个月零几天。这就是为什么您会收到这样的结果。

07-24 15:17