你问:
我想有一个函数,比较两个日期,如果(秒> 60),那么它返回分钟,如果(分钟> 60)返回小时,如果(小时> 24)返回天,等等。
我假设您正在尝试构建两个日期之间经过时间的字符串表示。而不是自己写代码来做这件事,苹果已经有了一个专门设计来做这件事的类。也就是说,使用DateComponentsFormatter,将allowedUnits设置为对你的应用有意义的任何值,将unitsStyle设置为你想要的任何值(例如.full),然后调用string(from:to:)。
例如,在Swift 3中:
let previousDate = ...
let now = Date()
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [.month, .day, .hour, .minute, .second]
formatter.maximumUnitCount = 2 // often, you don't care about seconds if the elapsed time is in months, so you'll set max unit to whatever is appropriate in your case
let string = formatter.string(from: previousDate, to: now)
这也将本地化对应于相关设备的字符串。
或者,在Swift 2.3中:
let previousDate = ...
let now = NSDate()
let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = .Full
formatter.allowedUnits = [.Month, .Day, .Hour, .Minute, .Second]
formatter.maximumUnitCount = 2
let string = formatter.stringFromDate(previousDate, toDate: now)
如果您正在寻找实际的数值,只需使用dateComponents。例如,在Swift 3中:
let components = Calendar.current.dateComponents([.month, .day, .hour, .minute, .second], from: previousDate, to: now)
或者,在Swift 2.3中:
let components = NSCalendar.currentCalendar().components([.Month, .Day, .Hour, .Minute, .Second], fromDate: previousDate, toDate: now, options: [])