1

I want to check if a date is between two dates but the result of my code is giving me wrong result can you check with me please. thank you for your help! this is my code

extension Date{
func isBetweenDates(beginDate: Date, endDate: Date) -> Bool
{
    if self.compare(beginDate) == .orderedAscending
    {
        return false
    }

    if self.compare(endDate) == .orderedDescending
    {
        return false
    }

    return true
   }
 }

 override func viewDidLoad() {
    let result0 =  "08-01-2019".date(format: "dd-MM-YYYY")!.isBetweenDates(beginDate: "01-01-2019".date(format: "dd-MM-YYYY")!, endDate: "09-01-2019".date(format: "dd-MM-YYYY")!)

    let result1 = "04-01-2019".date(format: "dd-MM-YYYY")!.isBetweenDates(beginDate: "06-01-2019".date(format: "dd-MM-YYYY")!, endDate: "08-01-2019".date(format: "dd-MM-YYYY")!)

    let result2 = "05-01-2019".date(format: "dd-MM-YYYY")!.isBetweenDates(beginDate: "01-01-2019".date(format: "dd-MM-YYYY")!, endDate: "04-01-2019".date(format: "dd-MM-YYYY")!)

    let result3 = "06-01-2018".date(format: "dd-MM-YYYY")!.isBetweenDates(beginDate: "01-01-2019".date(format: "dd-MM-YYYY")!, endDate: "08-01-2019".date(format: "dd-MM-YYYY")!)

 }

and the output : result0 = true , result1 = true ,result2 =true ,result3 = false ,or they should be result0 = true , result1 = false ,result2 = false ,result3 = false ,

mark
  • 327
  • 1
  • 2
  • 12

1 Answers1

1

In Swift, Date is comparable.

Which means you can compare two dates using this code...

date1 < date2

The compare function you are using is an old function that has come or from ObjectiveC. I presume you have found it on an old tutorial or something?

Anyway, just do something like...

return date1 < self && self < date2

In your function.

That will return true if self is between date1 and date2.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
  • Hey Fogmeister ! thank you for your reply, I tested your code and the output is : result0:false , result1:false , result2:false , result3:false but the first result must be true – mark Jul 06 '19 at 19:09
  • 1
    change `dd-MM-YYYY` to `dd-MM-yyyy` – Leo Dabus Jul 06 '19 at 19:10
  • 1
    Btw you can use pattern match operator wit dates as well `func isBetween(start: Date, end: Date) -> Bool { return start...end ~= self }` – Leo Dabus Jul 06 '19 at 19:16