let date1Str = "2016/09/30"
let date2Str = "2021/12/01"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"
let date1 = dateFormatter.dateFromString(date1Str)
let date2 = dateFormatter.dateFromString(date2Str)
let calendar = NSCalendar.currentCalendar()
let unitFlags:NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month , NSCalendarUnit.Day , NSCalendarUnit.Hour , NSCalendarUnit.Minute , NSCalendarUnit.Second]
let components = calendar.components(unitFlags, fromDate: date1!, toDate: date2!, options: NSCalendarOptions.init(rawValue: 0))
let timeDifference = "\(components.year)" + "年" + "\(components.month)" + "个月"
let timeDifferences = "两个日期的时间差是:" + timeDifference + "\(components.day)" + "天"
print(components.hour)
print(components.second)
如果你只是想计算两个月份的时间差
日期格式应设置为 yyyy/MM
同理 年/时/秒 so easy