dateComponents(_,from,to)返回错误的月数

时间:2016-09-14 10:02:11

标签: ios swift nsdate nscalendar nsdatecomponents

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

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还是什么?如果是这样的话,我需要一种新的方法来计算这里的月数。

1 个答案:

答案 0 :(得分:0)

我有同样的问题,但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个月和几天。这就是你收到这样结果的原因。