Check if date falls between 2 dates

后端 未结 6 1754
栀梦
栀梦 2020-12-08 13:43

I have this code where convert a String into a date object

let date2 = KeysData[indexPath.row][\"starttime\"] as? String

let dateFormatter = NSDateFormatter         


        
6条回答
  •  粉色の甜心
    2020-12-08 14:29

    Swift ≧ 3

    Swift 3 makes this a lot easier.

    let fallsBetween = (startDate ... endDate).contains(Date())
    

    Now that NSDate is bridged to the value type Date and Date conforms to Comparable we can just form a ClosedRange and use the contains method to see if the current date is included.

    Caveat: endDate must be greater or equal startDate. Otherwise the range could not be formed and the code would crash with a fatalError.

    This is safe:

    extension Date {
        func isBetween(_ date1: Date, and date2: Date) -> Bool {
            return (min(date1, date2) ... max(date1, date2)).contains(self)
        }
    }
    

提交回复
热议问题