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

后端 未结 8 947
挽巷
挽巷 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")
    }
    
    0 讨论(0)
  • 2020-12-29 11:00

    This is the route I took in the end, which makes it easy to compare just the time of a Date in swift

    New Object Time:

    class Time: Comparable, Equatable {
    init(_ date: Date) {
        //get the current calender
        let calendar = Calendar.current
    
        //get just the minute and the hour of the day passed to it
        let dateComponents = calendar.dateComponents([.hour, .minute], from: date)
    
            //calculate the seconds since the beggining of the day for comparisions
            let dateSeconds = dateComponents.hour! * 3600 + dateComponents.minute! * 60
    
            //set the varibles
            secondsSinceBeginningOfDay = dateSeconds
            hour = dateComponents.hour!
            minute = dateComponents.minute!
        }
    
        init(_ hour: Int, _ minute: Int) {
            //calculate the seconds since the beggining of the day for comparisions
            let dateSeconds = hour * 3600 + minute * 60
    
            //set the varibles
            secondsSinceBeginningOfDay = dateSeconds
            self.hour = hour
            self.minute = minute
        }
    
        var hour : Int
        var minute: Int
    
        var date: Date {
            //get the current calender
            let calendar = Calendar.current
    
            //create a new date components.
            var dateComponents = DateComponents()
    
            dateComponents.hour = hour
            dateComponents.minute = minute
    
            return calendar.date(byAdding: dateComponents, to: Date())!
        }
    
        /// the number or seconds since the beggining of the day, this is used for comparisions
        private let secondsSinceBeginningOfDay: Int
    
        //comparisions so you can compare times
        static func == (lhs: Time, rhs: Time) -> Bool {
            return lhs.secondsSinceBeginningOfDay == rhs.secondsSinceBeginningOfDay
        }
    
        static func < (lhs: Time, rhs: Time) -> Bool {
            return lhs.secondsSinceBeginningOfDay < rhs.secondsSinceBeginningOfDay
        }
    
        static func <= (lhs: Time, rhs: Time) -> Bool {
            return lhs.secondsSinceBeginningOfDay <= rhs.secondsSinceBeginningOfDay
        }
    
    
        static func >= (lhs: Time, rhs: Time) -> Bool {
            return lhs.secondsSinceBeginningOfDay >= rhs.secondsSinceBeginningOfDay
        }
    
    
        static func > (lhs: Time, rhs: Time) -> Bool {
            return lhs.secondsSinceBeginningOfDay > rhs.secondsSinceBeginningOfDay
        }
    }
    

    Date Extension for easy access: //Adds ability to just get the time from a date:

    extension Date {
        var time: Time {
            return Time(self)
        }
    }
    

    Example:

    let firstDate = Date()
    let secondDate = firstDate
    
    //Will return true
    let timeEqual = firstDate.time == secondDate.time
    
    0 讨论(0)
提交回复
热议问题