DSmith DSmith - 1 year ago 93
iOS Question

Comparing Weekdays NSDate

My goals:

  • Determine current day of the week (Sun = 1, Mon = 2, etc.)

    so that i can
    (if dayInt == 2){ ...

  • Then compare current time to set time forming a nested if with the statement above

    (if curTime > 9:00am && curTime < 11:00am){...

I've researched this topic and found the below code is a somewhat popular way of doing the first objective. I found the below code at

iPhone - how may I check if a date is Monday?

However, for some reason it causes a breakpoint in my code. It tells me to replace
(which I do) and have
be a
(which I have tried), but these still do not work.

It builds but then causes a breakpoint. If
is an
it says the value is 0, but if it is
it comes out as 256. I don't really see a need for it to be long though. Any ideas?

NSDate* curDate = [NSDate date];
int dayInt = [[[NSCalendar currentCalendar] components: NSWeekdayCalendarUnit fromDate: curDate] weekday];

Answer Source

Your code works just fine for me once I apply the changes you describe:

NSDate* curDate = [NSDate date];
NSInteger dayInt = [[[NSCalendar currentCalendar] components: NSCalendarUnitWeekday fromDate: curDate] weekday];
NSLog(@"Today's day of the week = %ld", dayInt);

Here is what I mean by breaking it into smaller steps for debugging:

NSDate* curDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components;
components = [calendar components: NSWeekdayCalendarUnit fromDate: curDate];
NSInteger dayInt = 0;
dayInt = [components weekday];
NSLog(@"Today's day of the week = %ld", dayInt);

When you make each line of your code contain at most one method call then it's much easier to step through it in the debugger and see what's happening. The example above is a little extreme to make a point, but in general I prefer to use temporary variables and series of simpler statement rather than a big complex statement. It makes it easier to read and debug, and the compiler optimizes away the temporary variables so there's rarely ANY difference in performance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download