Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check time overlap in swift?

I have 4 startTime datePicker and 4 endTime datePicker in my View. I want to check time is overlap or not.

Ex. slot 1 = 09:00 - 12:00
slot 2 = 08:00 - 11:00
slot 3 = 05:00 - 10:30
slot 4 = 11:00 - 16:00

I convert this time to decimal with using this formula:

(Minutes + (Hours*6))/10

Now I have decimal time, So I tried below code:

for item in validationArray! {
            let startIndexvalue:Int = item["startTime"]!
            let stopIndexvalue:Int = item["stopTime"]!

            print(startIndexvalue)
            print(stopIndexvalue)
            print(fastLinkStartTime)

            if stopIndexvalue > startIndexvalue {
                if startIndexvalue ... stopIndexvalue ~= fastLinkStartTime {

                    if startIndexvalue == 0 {
                        validationTimeDic["startTime"] = fastLinkStartTime
                        timeDic["startTime"] = hours + "0"
                    }

                    else {
                        showValidationAlert(title: NSLocalizedString("You can not select time in between existing time slot.", comment: ""), message: "")
                        DispatchQueue.main.async {
                            self.StartTime.text = "--:--"
                        }

                        validationTimeDic["startTime"] = 0
                        timeDic["startTime"] = "--:--"
                    }

                    validationArray?[currentRow] = validationTimeDic
                    self.currentObject!.validationData[currentSection.description] = validationArray

                    array?[currentRow] = timeDic
                    self.currentObject!.mondayToSundayData[currentSection.description] = array

                    print(self.currentObject!.validationData)

                }
            }

Please give me any idea to do this?

like image 359
Dhasal Avatar asked Oct 16 '25 13:10

Dhasal


1 Answers

You need to check if two Date ranges overflaps. This you can do by checking if one ClosedRange<Date> overlaps the other

let isOverlapping = (startDate1...endDate1).overlaps(startDate2...endDate2)

But for your case, you don’t want to append this time (in your case Int index) to array if it overlaps with any other time in array, so before you append this new time check if overlaps with some other time. If doesn’t append it, if does, do whatever you want to.

let array: [[String: Int]] = ...
let newStartIndex: Int = ...
let newEndIndex: Int = ...
let isOverlapping = array.allSatisfy { $0["startTime"] <= newEndIndex && newStartIndex <= $0["stopTime"]}
like image 177
Robert Dresler Avatar answered Oct 18 '25 04:10

Robert Dresler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!