4

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;

}
Vladimir Stazhilov
  • 1,956
  • 4
  • 31
  • 63

2 Answers2

9

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

Joshua Weinberg
  • 28,598
  • 2
  • 97
  • 90
4

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;
yuji
  • 16,695
  • 4
  • 63
  • 64
  • Well, and it won't depend on System Local Settings? – Vladimir Stazhilov Mar 21 '12 at 17:26
  • 1
    Yes, the better solution will be using conditions if(weekday>1) { weekday--; } else weekday=7; – Vladimir Stazhilov Mar 21 '12 at 17:29
  • Thanks @yAak; fixed my answer. Vova: no, did read the `NSDateComponents` documentation on `weekDay`? "Weekday units are the numbers 1 through n, where n is the number of days in the week. For example, in the Gregorian calendar, n is 7 and Sunday is represented by 1." Since you're using a specific calendar instead of using the system calendar, you'll always get the same result. – yuji Mar 21 '12 at 17:32
  • That reduces to europeanWeekday = weekday ... :[ i was just fiddling with this on paper too, so dont feel bad, haha. – MechEthan Mar 21 '12 at 17:39
  • Un-downvoted since you fixed! However, Joshua's answer to use `[NSCalendar setFirstWeekday:...]` is probably the best for others coming to this topic. – MechEthan Mar 21 '12 at 17:59
  • Thanks, and agreed. I had upvoted Joshua's answer already, but I'll edit my answer to mention `setFirstWeekday` as well. – yuji Mar 21 '12 at 18:01
  • `NSCalendar`'s `firstWeekday` property [is ignored by the `NSDateComponents`' `weekday` property](https://stackoverflow.com/a/11022360/865175). – Iulian Onofrei May 24 '17 at 10:16