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

后端 未结 8 962
挽巷
挽巷 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:57

    There's no standard type for a time-of-day. A reasonable type to start with is just a tuple:

    typealias TimeOfDay = (hour: Int, minute: Int, second: Int)
    

    To create these TimeOfDay values, you'll need a Calendar. By default, a Calendar uses the device's system-wide time zone. If you don't want that, set the Calendar's time zone explicitly. Example:

    var calendar = Calendar.autoupdatingCurrent
    calendar.timeZone = TimeZone(abbreviation: "UTC")!
    

    Now you can use a DateFormatter to convert strings to Dates (if necessary), and then use calendar to extract the time-of-day components from the Dates:

    let strings: [String] = ["2017-01-13 11:40:17 +0000", "2016-03-15 10:22:14 +0000"]
    let parser = DateFormatter()
    parser.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
    let timesOfDay: [TimeOfDay] = strings.map({ (string) -> TimeOfDay in
        let components = calendar.dateComponents([.hour, .minute, .second], from: parser.date(from: string)!)
        return (hour: components.hour!, minute: components.minute!, second: components.second!)
    })
    
    Swift.print(timesOfDay)
    // Output: [(11, 40, 17), (10, 22, 14)]
    

    Finally, you can compare these TimeOfDay values. Swift comes with standard comparison operators for tuples whose elements are Comparable, so this TimeOfDay type qualifies. You can just say this:

    if timesOfDay[0] < timesOfDay[1] {
        Swift.print("date[0] comes first")
    } else if timesOfDay[0] == timesOfDay[1] {
        Swift.print("times are equal")
    } else {
        Swift.print("date[1] comes first")
    }
    

提交回复
热议问题