快速比较DateComponents

问题描述

在Swift中,有没有一种方便的说法,例如15个月大于1年而1周小于10天?我觉得DateComponents最能代表我的需求,所以我需要以下东西:

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

但是据我所知,目前,DateComponents尚不具备可比性(二进制运算符'>'不能应用于两个'DateComponents'操作数)。

所以也许有人可以帮助我纯粹地迅速找到解决方案,或者使用一些库?预先谢谢你!

解决方法

您可以从DateComponents创建日期并进行比较。您可以使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)!
    }
}
    

然后您可以进行这些比较:

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

您可能还想将其设为Equatable

extension DateComponents: Equatable {
    public static func == (lhs: DateComponents,to: now)! == calendar.date(byAdding: rhs,to: now)!
    }
}

免责声明:此修订后的答案以当前日期/时间为参考,以确保对天和月进行有意义的比较(因为每月的天数可以更改)。 “如果一个月内有超过30天”之类的问题只有在呼叫者提供参考日期或我们使用“现在”(这就是我上面所做的事情)的情况下才有意义。

请注意,通过使用“现在”作为参考日期,然后进行类似“较大,24小时或1天”的比较,现在将包括夏令时(例如,取决于您的日历是“向前”还是“向下”)退回”,或者在大多数情况下完全没有改变。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...