简体   繁体   English

比较 swift 中的 DateComponents

[英]Compare DateComponents in swift

Is there any convenient way in Swift to say that, for example, 15 months is more than 1 year and 1 week is less than 10 days? Swift有没有方便的说法,比如15个月大于1年,1周小于10天? I feel like DateComponents represents my needs best, so I need something like:我觉得DateComponents最能代表我的需求,所以我需要这样的东西:

DateComponents(year: 1) > DateComponents(month: 15) // => false
DateComponents(day: 10) > DateComponents(weekOfMonth: 1) // => true

But currently in swift DateComponents are not comparable (Binary operator '>' cannot be applied to two 'DateComponents' operands), as I understand.但据我了解,目前在 swift DateComponents 中不可比较(二元运算符“>”不能应用于两个“DateComponents”操作数)。

So maybe anyone can help me to find the solution with pure swift, or using some library?所以也许任何人都可以帮助我找到纯 swift 或使用某些库的解决方案? Thank you in advance!先感谢您!

You can create dates from the DateComponents and compare them.您可以从DateComponents创建日期并比较它们。 You can make DateComponents conform to Comparable :您可以使DateComponents符合Comparable

extension DateComponents: Comparable {
    public static func < (lhs: DateComponents, rhs: DateComponents) -> Bool {
        let now = Date()
        let calendar = Calendar.current
        return calendar.date(byAdding: lhs, to: now)! < calendar.date(byAdding: rhs, to: now)!
    }
}
    

Then you can do those comparisons:然后你可以做这些比较:

DateComponents(year: 1) > DateComponents(month: 15) // => false
DateComponents(day: 10) > DateComponents(weekOfMonth: 1) // => true

You might also want to make it Equatable :您可能还想让它Equatable

extension DateComponents: Equatable {
    public static func == (lhs: DateComponents, rhs: DateComponents) -> Bool {
        let now = Date()
        let calendar = Calendar.current
        return calendar.date(byAdding: lhs, to: now)! == calendar.date(byAdding: rhs, to: now)!
    }
}

Disclaimer: This revised answer is using the current date/time as the reference to ensure meaningful comparison of days and months (give that the number of days per month can change).免责声明:此修改后的答案使用当前日期/时间作为参考,以确保对天数和月份进行有意义的比较(假设每个月的天数可以更改)。 Questions like “are there more than 30 days in a month” only makes sense if the caller supplies a reference date or we use “now” (which is what I've done above).只有当来电者提供参考日期或我们使用“现在”(这是我在上面所做的)时,“一个月中是否有超过 30 天”这样的问题才有意义。

Note, by using “now” as the reference date, then comparisons like “which is greater, 24 hours or 1 day” will now incorporate daylight savings (eg, depending upon whether your calendar will “spring forward”, “fall back”, or, the vast majority of the time, not change at all).请注意,通过使用“现在”作为参考日期,那么像“24 小时或 1 天哪个更大”这样的比较现在将包含夏令时(例如,取决于您的日历是否会“提前”、“后退”、或者,绝大多数时候,根本没有改变)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM