How to find weekday from today's date using NSDate?

后端 未结 5 2020
春和景丽
春和景丽 2020-12-05 07:13

I know that I can figure out today\'s date by [NSDate date]; but how would I find out today day of the week, like Saturday, Friday etc.

I know that

5条回答
  •  佛祖请我去吃肉
    2020-12-05 07:39

    NSCalendar* cal = [NSCalendar currentCalendar];
    NSDateComponents* comp = [cal components:NSCalendarUnitWeekday fromDate:[NSDate date]];
    return [comp weekday]; // 1 = Sunday, 2 = Monday, etc.
    

    See @HuguesBR's answer if you just need the weekday without other components (requires iOS 8+).

    NSInteger weekday = [[NSCalendar currentCalendar] component:NSCalendarUnitWeekday 
                                                       fromDate:[NSDate date]];
    

    (If you don't get a correct answer, check if you have mistyped NSCalendarUnitWeekday with other week-related components like NSCalendarUnitWeekdayOrdinal, etc.)


    Swift 3:

    let weekday = Calendar.current.component(.weekday, from: Date())
    // 1 = Sunday, 2 = Monday, etc.
    

提交回复
热议问题