Check if NSDate is Monday / Tue / etc.

I have an iOS app that needs to set several different date stamps to match the current day. For this I use NSDate

and NSDateFormatter

. However, there is something that I'm not sure about: if the user has an iOS device with their language / localization set to something other than English, then my if statements will execute that check if there is currently time is "monday" or "tuesday", stop working?

Here is my code:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyyMMdd";
NSDate *date = [NSDate date];

dateFormatter.dateFormat = @"EEEE";
NSString *dayString = [[dateFormatter stringFromDate:date] capitalizedString];
NSLog(@"Day: %@", dayString);


if ([dayString isEqualToString:@"Monday"]) {

}

else if ([dayString isEqualToString:@"Tuesday"]) {

}

else if ([dayString isEqualToString:@"Wednesday"]) {

}

else if ([dayString isEqualToString:@"Thursday"]) {

}

else if ([dayString isEqualToString:@"Friday"]) {

}

else if ([dayString isEqualToString:@"Saturday"]) {

}

else if ([dayString isEqualToString:@"Sunday"]) {

}

      

+3


source to share


2 answers


You can use the following program.



NSDateComponents *component = [[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:[NSDate date]];

switch ([component weekday]) {
    case 1:
        //Sunday
        break;
    case 2:
        //Monday
        break;
    ...
    case 7:
        //Saturday
        break;
    default:
        break;
}

      

+14


source


While the using answer NSDateComponents

is the best option, another possibility that works with the day of the week string:



NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"EEEE";
NSDate *date = [NSDate date];
NSString *dayString = [dateFormatter stringFromDate:date];

NSInteger weekdayNum = [[dateFormatter weekdaySymbols] indexOfObject:dayString];
switch (weekdayNum) {
    case 0:
        //Sunday
        break;
    case 1:
        //Monday
        break;
    ...
    case 6:
        //Saturday
        break;
    default:
        break;
}

      

+4


source







All Articles