Supertecnoboff
Supertecnoboff

Reputation: 6606

Check whether NSDate is Monday/Tues/etc

I have an iOS app which needs to set a few different date labels according to the current day. I am using NSDate and NSDateFormatter to do this. However there is something I am not sure about: if the user has an iOS device with their language/localisation set to something other than English, then will my if statements that check to see if it is currently "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"]) {

}

Upvotes: 3

Views: 5571

Answers (3)

pableiros
pableiros

Reputation: 16032

On you Swift, you can do this:

let calendar: Calendar = Calendar.current
let isMonday = calendar.component(Calendar.Component.weekday, from: self) == 2

Or you can use this Date extension to get the week day of a date:

extension Date {

    enum WeekDay: Int {
        case sunday = 1
        case monday
        case tuesday
        case wednesday
        case thursday
        case friday
        case saturday
    }

    func getWeekDay() -> WeekDay {
        let calendar = Calendar.current
        let weekDay = calendar.component(Calendar.Component.weekday, from: self)
        return WeekDay(rawValue: weekDay)!
    }
}

let date = Date()
date.getWeekDay()

Upvotes: 2

deoKasuhal
deoKasuhal

Reputation: 2897

You can use 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;
}

Upvotes: 19

rmaddy
rmaddy

Reputation: 318814

While the answer using NSDateComponents is the best option, another possibility that works with the weekday string would be:

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;
}

Upvotes: 5

Related Questions