ios - swift 2 : How to calculate the number of days between current iPhone time and date I provide

标签 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

最佳答案

这应该有效:

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

您传递开始日期和结束日期并返回一个整数数组。

示例:

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

关于ios - swift 2 : How to calculate the number of days between current iPhone time and date I provide,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32994063/

相关文章:

swift - 查询中出现向下错误

ios - 如何限制我在 iOS(swift)/Firebase 应用程序上为每个用户提供的存储空间?

swift - 用户输入作为全局变量以显示来自不同 View 的文本

c++ - 在 Qt 中注册 iOS 默认用户首选项

iphone - 我可以在多台机器上使用同一个 iPhone 开发者计划帐户吗?

iphone - 将 UIActionSheet 按钮与当前 IBAction 链接

ios - 使用 'Codable'解码数据

ios - 调整导航 Controller 中自定义 UIBarButtonItem 的大小

iphone - 在 iOS6 中启用哪些 API 来实现视频稳定?

ios - 检查选定的 UITableViewCell 的值是什么