[分享]iOS开发-通过日期求星期

通过日期求星期

-(NSString*)fromDateToWeek:(NSString*)selectDate
{
    NSInteger yearInt = [selectDate substringWithRange:NSMakeRange(0, 4)].integerValue;//取第0~4位
    NSInteger monthInt = [selectDate substringWithRange:NSMakeRange(4, 2)].integerValue;//取第4位的后两位
    NSInteger dayInt = [selectDate substringWithRange:NSMakeRange(6, 2)].integerValue;//取第6位的后两位
    int c = 20;//世纪
    long int y = yearInt -1;//年
    long int d = dayInt;
    long int m = monthInt;
    int w =(y+(y/4)+(c/4)-2*c+(26*(m+1)/10)+d-1)%7;
    NSString *weekDay = @"";
    switch (w) {
        case 0:
            weekDay = @"星期日";
            break;
        case 1:
            weekDay = @"星期一";
            break;
        case 2:
            weekDay = @"星期二";
            break;
        case 3:
            weekDay = @"星期三";
            break;
        case 4:
            weekDay = @"星期四";
            break;
        case 5:
            weekDay = @"星期五";
            break;
        case 6:
            weekDay = @"星期六";
            break;
        default:
            break;
    }
    return weekDay;
}

获取当前年月日,星期

-(int)getCurrentTimeWith:(State)state
{
    NSDate* date = [NSDate date];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* comps = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit) fromDate:date];
    switch (state) {
        case year:{
            return [comps year];
        }
            break;
        case month:{
            return [comps month];
            break;
        }
        case day:{
            return [comps day];
            break;
        }
        case week:{
            return [comps weekday]-1>0?[comps weekday]-1:7;
            break;
        }
        default:
            break;
    }
}

h.
#import <UIKit/UIKit.h>
#import "InfoView.h"
typedef enum{
    year=0,
    month,
    day,
    week
}State;

//似乎是个可以获得日历属性的方法
NSCalendar日历
    原文作者:ShevaKuilin
    原文地址: https://segmentfault.com/a/1190000004535000
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞