我如何计算两个日期之间的天数?

时间:2016-02-18 08:11:32

标签: xcode swift nsdate

希望有人能帮助我。我需要计算日期之间的天数。流程是:

  • 选择日期
  • 按年计算的新日期(例如2年)
  • 获取"选择日期"之间的日子。和#34;新约会"

1 个答案:

答案 0 :(得分:1)

试用此代码,针对Swift 2.0进行了更新

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

let first = "2010-09-01"
let firstDate = dateFormatter.dateFromString(first)!
let last = "2010-09-05"
let lastDate = dateFormatter.dateFromString(last)!

let currentCalendar = NSCalendar.currentCalendar()
let timeUnitDay = NSCalendarUnit.Day

let daysBetween = currentCalendar.components(timeUnitDay, fromDate: firstDate, toDate: lastDate, options: NSCalendarOptions.MatchStrictly)

print(daysBetween.day)