简体   繁体   中英

dateComponents(_, from, to) returning wrong number of months

I have a function to create a date...

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

It just takes the day, month and year as a convenience.

So I create two dates.

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

And then calculate the number of months between them...

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

print(components.month) // returns 1

Shouldn't this be 2? How is the month component calculated? Is it just the number of days divided by 30 or something? If so I'll need a new way of calculating the number of months here.

I have the same issue, but NSCalendar is working fine this code example proofs this.

    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

In you're case difference is 1 month and a few days. And that is why you receive such result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM