Check if date falls between 2 dates

后端 未结 6 1751
栀梦
栀梦 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:20

    For Swift 4.2 I used this extension based on answer above:

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

    But be careful. If this extension doesn't include your start date (date1), then check the time of your dates. May be you'll need to cut the time from dates to fix it. For example, like this:

    let myDateWithoutTime = Calendar.current.startOfDay(for: myDate)
    

提交回复
热议问题