Search code examples
objective-cnsdatedayofweek

Objective-c get day of week in number starting with Monday, NOT Sunday


I'm making my custom calendar view for an app for the European market. In a function I should get number of day of week... I do, but it returns the number of the day of week starting with Sunday. How should I hardcode returning this number starting with Monday? Thanks Here is what I have so far:

-(int)getWeekDay:(NSDate*)date_
{
    NSLocale *frLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"];

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [gregorian setLocale:frLocale];
    NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:date_];
    int weekday = [comps weekday];

    NSLog(@"Week day is %i", weekday);
    return weekday;

}

Solution

  • The best way to do this would be to use [NSCalendar setFirstWeekday:], as Joshua said in his answer.

    Otherwise, you can do integer arithmetic. Vova's method is straightforward:

    if (weekday>1)
        weekday--; 
    else 
        weekday=7;
    

    This one below works too, although it's a bit confusing:

    int europeanWeekday = ((weekday + 5) % 7) + 1;