I created a category for NSDate that can create a string representation of a date with the name of the week of the week, like Thursday, January 5th.
I want to get the weekday index and use a custom array of days of the week, which are stored in plist and localized in English and Spanish.
However, using NSDateComponents gives me unexpected results. I request both NSWeekdayOrdinalCalendarUnit and NSWeekdayCalendarUnit , and I logged the results, and I get the following example:
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayOrdinalCalendarUnit | NSWeekdayCalendarUnit fromDate:self]; NSInteger weekdayOrdinal = [components weekdayOrdinal]; NSInteger weekdayNonOrdinal = [components weekday]; NSLog(@"Date: %@", [self description]); NSLog(@"Device oridinal weekday: %d", weekdayOrdinal); NSLog(@"Device non-oridinal weekday: %d", weekdayNonOrdinal);
2012-01-06 15:05: 56.492 MyApp [964: 11903] Date: 2012-01-05 16:13:46 +0000
2012-01-06 15:05: 56.492 MyApp [964: 11903] Device on the day of the week: 1
2012-01-06 15: 05: 56.493 MyApp [964: 11903] A device without an ordinary weekday: 5
This day should be on Thursday, the serial number should be 4 and not indicate 5
I do not understand where 1 comes from.
I found a way to configure this to make sure we use the gregorian calendar with NSDateFormatter and specifying NSCalendar (with the first date of the week on Monday) as follows:
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]; [gregorian setFirstWeekday:2]; NSUInteger adjustedWeekdayOrdinal = [gregorian ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:self]; NSDateFormatter *weekdayF = [[[NSDateFormatter alloc] init] autorelease]; [weekdayF setDateFormat: @"EEEE"]; [weekdayF setCalendar:gregorian]; [weekdayF setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_UK"]]; NSLog(@"The day of the week is: %@", [weekdayF stringFromDate:self]);
This will give me what I want, but now I need to save the locale id in plist for use in Spanish, what I would prefer to save is the first instance with NSDateComponents , but I donβt understand why I sometimes get a funny value .
I found a solution to tune the index using this solution: stack overflow
However, to be honest, I would not want to use this together with NSDateComponents , I would prefer to use NSDateFormatter , but in general it would be great to fix the first example, which gives me a false weekdayOrdinal value.
Any ideas on this?