Vladimir Stazhilov
Vladimir Stazhilov

Reputation: 1954

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;

}

Upvotes: 4

Views: 4320

Answers (2)

yuji
yuji

Reputation: 16725

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;

Upvotes: 4

Joshua Weinberg
Joshua Weinberg

Reputation: 28688

You should use [NSCalendar setFirstWeekday:] to do this.

Upvotes: 9

Related Questions