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

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

    My solution for comparing two times of day while ignoring the date:

    let date1 = some time as a date
    let date2 = some other time as a date
    
    let time1 = 60*Calendar.current.component(.hour, from: date1!) + Calendar.current.component(.minute, from: date1!)
    let time2 =  60*Calendar.current.component(.hour, from: date2!) + Calendar.current.component(.minute, from: date2!)
    

    Now you can compare the integers time1 and time2 without regard to the day. You could add the seconds/60 if you need more precision.

提交回复
热议问题