Objective-C判断某日期为星期几

各种google没找到完整的判断星期几的demo,参考部分前辈的代码,自己琢磨写了个方法,大神看了莫拍。

- (NSString*)weekdayStringFromDate:(NSString*)inputDate {
    //截取年月日
    NSString *year = [inputDate substringToIndex:4];
    int yearNum = [year intValue];
    NSString *mon0 = [inputDate substringFromIndex:4];
    NSString *mon = [mon0 substringToIndex:2];
    int monNum = [mon intValue];
    NSString *day = [inputDate substringFromIndex:6];
    int dayNum = [day intValue];
    //定义一个NSDateComponents对象,设置为导入的时间点
    NSDateComponents *_comps = [[NSDateComponents alloc] init];
    [_comps setDay:dayNum];
    [_comps setMonth:monNum];
    [_comps setYear:yearNum];
    //一周的数组
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null],@"星期天",  @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];
    //定义一个遵循某个历法的日历对象
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *_date = [gregorian dateFromComponents:_comps];
    NSDateComponents *weekdayComponents =
    [gregorian components:NSCalendarUnitWeekday fromDate:_date];
    int _weekday = [weekdayComponents weekday];
    //返回星期几
    return [weekdays objectAtIndex:_weekday];
    
}
    原文作者:Xayoung_Coder
    原文地址: https://www.jianshu.com/p/0cd6c4bfd00c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞