根据日期字符串转化为星期几的函数

- (NSString*)WeekdayStringFromDateString:(NSString *)dateString {

    NSDateFormatter *dateFormatter = [[NSDateFormatteralloc] init]; 

    [dateFormatter setDateFormat: @"yyyy-MM-dd"]; 

    NSDate *Date= [dateFormatter dateFromString:dateString];

    NSArray *weekdays = [NSArrayarrayWithObjects: [NSNullnull], @"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];

    NSCalendar *calendar = [[NSCalendaralloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSTimeZone *timeZone = [[NSTimeZonealloc] initWithName:@"Asia/Shanghai"];

    [calendar setTimeZone: timeZone];

    NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit;

    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:Date];  

    return [weekdays objectAtIndex:theComponents.weekday];

}

二.

- (NSString*)getWeekDayWithYear:(NSString*)year month:(NSString*)month day:(NSString*)day

{

    NSInteger yearInt   = [year integerValue];

    NSInteger monthInt  = [month integerValue];

    NSInteger dayInt    = [day integerValue];

    int c = 20;//世纪

    int y = (int)yearInt -1;//年

    int d = (int)dayInt;

    int m = (int)monthInt;

    int w =(y+(y/4)+(c/4)-2*c+(26*(m+1)/10)+d-1)%7;

    NSString *weekDay = @"";

    switch (w) {

        case0: weekDay = @"星期日";    break;

        case1: weekDay = @"星期一";    break;

        case2: weekDay = @"星期二";    break;

        case3: weekDay = @"星期三";    break;

        case4: weekDay = @"星期四";    break;

        case5: weekDay = @"星期五";    break;

        case6: weekDay = @"星期六";    break;

        default:break;

    }

    return weekDay;

}

你可能感兴趣的:(根据日期字符串转化为星期几的函数)