检查NSDate是星期一还是星期二/等

时间:2015-05-20 21:44:00

标签: ios objective-c cocoa-touch date nsdate

我有一个iOS应用,需要根据当天设置几个不同的日期标签。我正在使用NSDateNSDateFormatter来执行此操作。然而,有一些我不确定的事情:如果用户的iOS设备的语言/本地化设置为英语以外的其他设置,那么我的if语句将检查当前是否是#34;星期一"或"星期二",停止工作?

这是我的代码:

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 个答案:

答案 0 :(得分:17)

您可以使用以下程序。

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

答案 1 :(得分:4)

虽然使用NSDateComponents的答案是最佳选择,但使用工作日字符串的另一种可能性是:

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

答案 2 :(得分:0)

在您的Swift上,您可以执行以下操作:

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

或者您可以使用此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()