malcommac / SwiftDate

🐔 Toolkit to parse, validate, manipulate, compare and display dates, time & timezones in Swift.
MIT License
7.63k stars 770 forks source link

Manage time intervals and check if date fall in an interval #73

Open jyounus opened 8 years ago

jyounus commented 8 years ago

Hey there,

I don't have time to create a PR right now, but thought I'd post my code here for you to update. The isInTimeRange function on line 639 isn't working properly.

Here's the modified version that works for me:

func isInTimeRange(minTime: String!, maxTime: String!, format: String?) -> Bool {
        /*let dateFormatter = NSDate.localThreadDateFormatter()
        dateFormatter.dateFormat = format ?? "HH:mm"
        dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
        let minTimeDate = dateFormatter.dateFromString(minTime)
        let maxTimeDate = dateFormatter.dateFromString(maxTime)*/

        let minArray = minTime.componentsSeparatedByString(":")
        let minTimeDate = NSDate().set(componentsDict: ["hour":Int(minArray[0])!, "minute":Int(minArray[1])!])

        let maxArray = maxTime.componentsSeparatedByString(":")
        let maxTimeDate = NSDate().set(componentsDict: ["hour":Int(maxArray[0])!, "minute":Int(maxArray[1])!])

        if minTimeDate == nil || maxTimeDate == nil {
            return false
        }
        let inBetween = (self.compare(minTimeDate!) == NSComparisonResult.OrderedDescending &&
            self.compare(maxTimeDate!) == NSComparisonResult.OrderedAscending)

        print("minTimeDate: \(minTimeDate)")
        print("maxTimeDate: \(maxTimeDate)")
        print("current: \(self)")

        return inBetween
    }

Basically I had to make sure that I create the new NSDate objects and set them to todays date. Your existing way was setting it to whatever the start date of the unix epoch time is again.

I can submit a PR over the next few days or so, unless you have time to just take the above code and maybe clean it up a bit yourself.

Thanks for the lib btw! :)

Hout commented 8 years ago

isInTimeRange is not currently in the v2 version. We should do something with time intervals alike the NSDateInterval class. Needs further investigation. What do you think @malcommac

Hout commented 8 years ago

@malcommac ?

malcommac commented 8 years ago

I'm finishing TimePeriod class; I think we could add a shortcut to manage time-only interval in NSDate/DateInRegion which uses TimePeriod methods. I'll post updated later this week.

malcommac commented 8 years ago

Scheduled for 4.2.0