在Swift中计算两个日期之间的时差 [英] Calculating the difference between two dates in Swift

查看:1107
本文介绍了在Swift中计算两个日期之间的时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了许多方法来根据特定的日期组成部分来计算两个日期之间的差异,例如(以天,小时,月等为单位)(请参见有关Stackoverflow的答案):

I've seen many approaches how to compute the difference between two dates in terms of a particular date component, e.g. in days, hours, months etc. (see 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 对象进行计算。像这样的

What I haven't seen is how to make calculations with the actual Date objects. Something like

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

我看过 DateInterval 类型,这是在iOS 10中引入的,但根据文档

I have seen the DateInterval type which as introduced in iOS 10 but according to the documentation


[it]并不支持反向间隔,即持续时间小于0且结束日期在时间上早于开始日期的间隔。

[it] does not support reverse intervals i.e. intervals where the duration is less than 0 and the end date occurs earlier in time than the start date.

很难用日期进行计算–特别是当您不知道哪个是较早的日期时。

That makes it inherently difficult to calculate with dates – especially when you don't know which one is the earlier date.

是否有任何简洁的方法来计算时间 Date 之间的直接差异(并将它们再次添加到 Date 实例中)无需计算他们的 timeIntervalSinceReferenceDate

Is there any clean and neat approach to compute time differences between Dates directly (and adding them to Date instances again) without computing with their timeIntervalSinceReferenceDate?

解决方案

我最终为 Date 创建了一个自定义运算符:

I ended up creating a custom operator for Date:

extension Date {

    static func - (lhs: Date, rhs: Date) -> TimeInterval {
        return lhs.timeIntervalSinceReferenceDate - rhs.timeIntervalSinceReferenceDate
    }

}

使用此运算符,我现在可以在更抽象的级别上计算两个日期之间的差,而无需关心 timeIntervalSinceReferenceDate 或确切的参考日期是-和而不损失精度,例如:

With this operator I can now compute the difference between two dates on a more abstract level without caring about timeIntervalSinceReferenceDate or what exactly the reference date is – and without losing precision, for example:

let delta = toDate - fromDate

很明显,我并没有做太多更改,但是对我来说,它更具可读性和结果:Swift具有 + 运算符已为 Date TimeInterval 实现:

Obviously, I didn't change much, but for me it's a lot more readable and consequent: Swift has the + operator already implemented for a Date and a TimeInterval:


/// Returns a `Date` with a specified amount of time added to it.
public static func + (lhs: Date, rhs: TimeInterval) -> Date


所以它已经在支持

Date + TimeInterval = Date

因此,它也应该支持

Date - Date = TimeInterval

在我看来,这就是-运算符的简单实现所添加的内容。现在,我可以简单地按照问题中所述的方式编写示例函数:

in my opinion and that's what I added with the simple implementation of the - operator. Now I can simply write the example function exactly as mentioned in my question:

func computeNewDate(from fromDate: Date, to toDate: Date) -> Date    
     let delta = toDate - fromDate // `Date` - `Date` = `TimeInterval`
     let today = Date()
     if delta < 0 {
         return today
     } else {
         return today + delta // `Date` + `TimeInterval` = `Date`
     }
}

很可能这是我目前尚不知道的一些缺点,我很喜欢听听您对此的想法。

It might very well be that this has some downsides that I'm not aware of at this moment and I'd love to hear your thoughts on this.

这篇关于在Swift中计算两个日期之间的时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆