I have to find the day that the 1st of each month falls on to be able to create a custom calendar; for instance, September 1, 2015 falls on a Tuesday, which makes Tuesday the first day of the month.
I have this code which works for English language countries, but for other countries, it fails because it doesn't translate correctly.
// build date as start of month
monthDateComponents.year = components.year;
monthDateComponents.month = components.month;
monthDateComponents.day = 1;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *builtDate =[gregorian dateFromComponents: monthDateComponents];
NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:@"E"];
NSString *firstDay = [df stringFromDate:builtDate];
// now, convert firstDay to the numeric day number
if([firstDay isEqual:NSLocalizedString(@"Sun",nil)])
return 7;
else if([firstDay isEqual:NSLocalizedString(@"Mon",nil)])
return 1;
else if([firstDay isEqual:NSLocalizedString(@"Tue",nil)])
return 2;
else if([firstDay isEqual:NSLocalizedString(@"Wed",nil)])
return 3;
else if([firstDay isEqual:NSLocalizedString(@"Thu",nil)])
return 4;
else if([firstDay isEqual:NSLocalizedString(@"Fri",nil)])
return 5;
else if([firstDay isEqual:NSLocalizedString(@"Sat",nil)])
return 6;
Is there a better way of doing this so I don't have to go through each country and find what the 3 character abbreviation for each day is? (for instance, in French, the day abbreviation for Saturday returns "sam.".) The way I have this coded now, I need to know each and every language that my app is localized for (10 of them) make it work correctly.
Thank you in advance.
try this, it uses a smart calendar calculation of NSCalendar.
NSDateComponents *components = [NSDateComponents new];
components.day = 1;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *firstDayOfMonth = [gregorian nextDateAfterDate:builtDate matchingComponents:components options: NSCalendarMatchNextTime | NSCalendarSearchBackwards];
NSInteger weekdayIndex = [gregorian component:NSCalendarUnitWeekday fromDate:firstDayOfMonth];
NSLog(@"weekday number: %ld", weekdayIndex);
return weekdayIndex;