Swift 2:如何计算当前iPhone时间和我提供的日期之间的天数

时间:2015-10-07 13:51:38

标签: ios iphone swift nsdate swift2

我看到很多帖子,但我无法解决问题。我需要知道从iPhone发布之日起过去了多少天/小时/分钟以及我提供的旧日期。我尝试了不同的教程并在stackoverflow中发布,但没有任何效果。请帮帮我谢谢。

class timeElapsed {

init?(startDate: NSDate, endDate: NSDate){

    let calendar = NSCalendar.currentCalendar()

    let components = calendar.components([.Day, .Month, .Year], fromDate: startDate, toDate: endDate, options: [])

   print(components.day)

return nil

}

使用此代码它可以工作,但它给了我7天的差异而不是11天的差异。实际上日期为endDate: 2015-10-07 14:27:53 +0000 startDate: 2015-09-26 15:17:55 +0000

1 个答案:

答案 0 :(得分:0)

这应该有效:

func timeBetween(startDate: NSDate, endDate: NSDate) -> [Int]
{
    let calendar = NSCalendar.currentCalendar()

    let components = calendar.components([.Day, .Month, .Year], fromDate: startDate, toDate: endDate, options: [])

    return [components.day, components.hour, components.minute]
}

您传递了开始日期和结束日期,并返回了一组int。

实施例

let nowDate:NSDate // current date
let historydate:NSDate // some old date

let timeSince:[Int] = timeBetween(historydate, endDate: nowDate)
timeSince[0] // days
timeSince[1] // hours
timeSince[2] // minutes
相关问题