How do you compare just the time of a Date in Swift?

后端 未结 8 981
挽巷
挽巷 2020-12-29 10:05

I have two Date Objects:

  1. 2017-01-13 11:40:17 +0000

  2. 2016-03-15 10:22:14 +0000

I need to compare

8条回答
  •  清酒与你
    2020-12-29 10:56

    This is very simple in Swift if you use Swifter Swift

    date1.day = 1
    date1.month = 1
    date1.year = 2000
    
    date2.day = 1
    date2.month = 1
    date2.year = 2000
    

    now you can use >,<,== operators on date1 and date2 to compare just the time components.

    edit - you could do this your self by extending the date class, for example swifter-swift does the bellow for the day component.

    public var day: Int {
            get {
                return Calendar.current.component(.day, from: self)
            }
            set {
                let allowedRange = Calendar.current.range(of: .day, in: .month, for: self)!
                guard allowedRange.contains(newValue) else { return }
    
                let currentDay = Calendar.current.component(.day, from: self)
                let daysToAdd = newValue - currentDay
                if let date = Calendar.current.date(byAdding: .day, value: daysToAdd, to: self) {
                    self = date
                }
            }
        } 
    

提交回复
热议问题