"hour" int taken from NSDate not behaving as expected at midnight??

Posted by Eric on Stack Overflow See other posts from Stack Overflow or by Eric
Published on 2010-04-05T23:00:14Z Indexed on 2010/04/05 23:03 UTC
Read the original article Hit count: 326

I feel like I've lost my mind. Can someone tell me what's going on here? Also, I'm sure there is a better way to do what I'm trying to do, but I'm not interested in that now. I'd just like to solve the mystery of why my ints are not responding to logic as expected.

// Set "At: " field close to current time
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH"];
int hour = [[dateFormatter stringFromDate:[NSDate date]] intValue]; 
[dateFormatter setDateFormat:@"mm"];
int minute = [[dateFormatter stringFromDate:[NSDate date]] intValue];
NSLog(@"currently %i:%i",hour, minute);

if(hour >= 12){ // convert to AM/PM
    selectedMeridiem = 1;
    if(hour != 12){
        hour = hour - 12;
    }
}
else{
    selectedMeridiem = 0;
}

selectedHour = hour - 1;

if(selectedHour <= 0){
    selectedHour = 11;
}

When I debug the above code with my clock set to 12:XX AM, the integer "hour" returned is 0. But then any if statements with the condition if(hour == 0) are not evaluated. Likewise, this would not be evaluated either: if(hour < 1). The code above puts the hour int into another int, selectedHour (don't worry about why I'm doing this for now), but selectedHour suffers from the same weird behavior; the if(selectedHour <= 0) line is never evaluated. Am I going crazy, or am I just an idiot? Maybe there's some behavior of 0 integers that I'm not aware of. All of my code runs fine as long as it's not 12:XX AM.

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about integers