1

In the app I'm fetching a value from core data (this value is a date) and comparing it to a time(in the format of a string) and doing actions accordingly. However for some reason the if statement just doesn't seem to work. No matter which time it is the result is always using value1 (time 0:00 to 5:30) for the division (please check code below). I have checked to see if the core data fetching has the correct name and yes it should be working. Anyone have any ideas?

func calculate() {

        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContext = appDelegate.managedObjectContext
        let fetchRequest = NSFetchRequest(entityName: "Settings")

        do {
            let results = try managedContext.executeFetchRequest(fetchRequest)
            Settings = results as! [NSManagedObject]

            for result in results as! [NSManagedObject] {

                correctionRatio = result.valueForKey("correctionRatio") as! Int
                target = result.valueForKey("targetbG") as! Int
                value1 = result.valueForKey("value1") as! Int
                value2 = result.valueForKey("value2") as! Int
                value3 = result.valueForKey("value3") as! Int
                value4 = result.valueForKey("value4") as! Int
                value5 = result.valueForKey("value5") as! Int

                if bGTextfield.text != "" && carbTextfield.text != "" {

                    current = Int(bGTextfield.text!)
                    carb = Int(carbTextfield.text!)

                    let currentTime = NSDate()
                    let timeFormatter = NSDateFormatter()
                    timeFormatter.locale = NSLocale.currentLocale()
                    timeFormatter.dateFormat = "HH:mm"
                    let time = timeFormatter.stringFromDate(currentTime)


                    if time > "00:00" && time < "5:30" {
                        food = carb / value1
                    } else if time > "5:31" && time < "11:00"{
                        food = carb / value2
                    } else if time > "11:01" && time < "17:00"{
                        food = carb / value3
                    } else if time > "17:01" && time < "21:30" {
                        food = carb / value4
                    } else if time > "21:31" && time < "23:59" {
                        food = carb / value5
                    }



                    if 4 ... 9 ~= Double(currentbG){

                        doseLabel.text = String(foodInsulin)


                    } else if 9.1 ... 100 ~= Double(currentbG) {

                        bgDiff = currentbG - targetbG
                        correction = bgDiff / correctionRatio
                        total = food + correctionInsulin

                        doseLabel.text = String(total)
                    }

    }

thanks

Antonio C
  • 71
  • 1
  • 9

4 Answers4

2

I've done something similar to this in a NSDate Extension:

private class func timeAsIntegerFromDate(date: NSDate) -> Int {
    let currentCal = NSCalendar.currentCalendar()
    currentCal.timeZone = NSTimeZone.localTimeZone()
    let comps: NSDateComponents = currentCal.components([NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: date)
    return comps.hour * 100 + comps.minute
}

private class func timeIsBetween(startDate: NSDate, endDate: NSDate) -> Bool {
    let startTime = NSDate.timeAsIntegerFromDate(startDate)
    let endTime = NSDate.timeAsIntegerFromDate(endDate)
    let nowTime = NSDate.timeAsIntegerFromDate(NSDate())

    if startTime == endTime { return false }

    if startTime < endTime {
        if nowTime >= startTime {
            if nowTime < endTime { return true }
        }
        return false
    } else {
        if nowTime >= startTime || nowTime < endTime {
            return true
        }
        return false
    }
}

I'm sure it can be cleaned up a bit and much improved upon. What I did was turn NSDate into Int and then checked which is larger smaller. The basic principle is that this multiplies the time by 100 and adds the minutes to the end of it and compares it.

jasonnoahchoi
  • 871
  • 5
  • 16
0

Just a hunch, but I don't think you can compare times with the > and < operators.

Time comparisons in swift

That post explains how to do it properly.

Also, you're storing the time as a string rather than a date. Store it as a date instead.

Community
  • 1
  • 1
Brendan Chang
  • 1,338
  • 2
  • 9
  • 10
  • hi , not exactly what I'm looking for. The comparison wouldn't help with me as I'm trying to find if the current time is within a range – Antonio C Jan 26 '16 at 21:48
  • You do a comparison test in your if statement. You are comparing two strings with > and < which won't work. – Brendan Chang Jan 26 '16 at 21:52
0

You're doing string comparisons for values that are inherently numeric. That's a bad idea in a couple of different ways, which accounts for your inaccurate results. You can compare strings like that, but the rules are not the same as for numeric comparisons.

If you want to compare times, compare times. You could start with something like:

let components = NSCalendar.currentCalendar().componentsInTimeZone(NSTimeZone.localTimeZone(), fromDate: NSDate())

From there, components will have numeric properties named hour and minute. Use those for your comparisons.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
0

You want to store your dates as NSDate if it's a date. Or as an Int16 if it's minutes of the day (minutes + 60 * hours such that 05:30 would be 5 * 60 + 30 = 330. Once you've done that it's trivial to create a predicate that matches those values that you're interested in.

Daniel Eggert
  • 6,665
  • 2
  • 25
  • 41