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

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

    Much simpler than accepted answer:

    SWIFT 4

    // date1 and date2 are the dates you want to compare
    
    let calendar = Calendar.current
    
    var newDate = Date(TimeIntervalSinceReferenceDate: 0) // Initiates date at 2001-01-01 00:00:00 +0000
    var newDate1 = Date(TimeIntervalSinceReferenceDate: 0) // Same as above
    
    // Recieving the components from the dates you want to compare 
    let newDateComponents = calendar.dateComponents([.hour, .minute], from: date1)!
    let newDate1Components = calendar.dateComponents([.hour, .minute], from: date2)!
    
    // Adding those components
    newDate = calendar.date(byAdding: newDateComponents, to: newDate)
    newDate1 = calendar.date(byAdding: newDate1Components, to: newDate1)
    

提交回复
热议问题