我见过许多方法如何根据特定的日期成分计算两个日期之间的差异,例如以天、小时、月等为单位(见this answer on Stackoverflow):
Calendar.current.dateComponents([.hour], from: fromDate, to: toDate).hour
Calendar.current.dateComponents([.day], from: fromDate, to: toDate).day
Calendar.current.dateComponents([.month], from: fromDate, to: toDate).month
我没有看到的是如何用实际的Date
个物体进行计算.差不多
func computeNewDate(from fromDate: Date, to toDate: Date) -> Date
let delta = toDate - fromDate
let today = Date()
if delta < 0 {
return today
} else {
return today + delta
}
}
我见过iOS 10中引入的DateInterval
类型,但根据文档
[it]不支持反向间隔,即持续时间小于0且结束日期早于开始日期的间隔.
这就使得计算日期本身就很困难——尤其是当你不知道哪一个是较早的日期时.
Is there any clean and neat approach to compute time differences between 100s directly(并再次将它们添加到Date
个实例中)without computing with their 102?