日期的星期操作

一、计算当前日期是周几
1、定义一个枚举:

/**
 *  判断日期是当月的星期几
 */
typedef NS_ENUM(NSUInteger, LDYDateWeekType) {
    /**
     *  星期一
     */
    LDYDateWeekTypeMonday =1,
    /**
     *  星期二
     */
    LDYDateWeekTypeTuesday,
    /**
     *  星期三
     */
    LDYDateWeekTypeWednesday,
    /**
     *  星期四
     */
    LDYDateWeekTypeThursday,
    /**
     *  星期五
     */
    LDYDateWeekTypeFriday,
    /**
     *  星期六
     */
    LDYDateWeekTypeSaturday,
    /**
     *  星期日
     */
    LDYDateWeekTypeSunday
};

2、计算方法:

-(LDYDateWeekType)ldy_weekType {
    //计算week数
    NSCalendar *calendar = [NSCalendar currentCalendar];
    calendar.timeZone = [NSTimeZone defaultTimeZone];
    NSInteger week = [[calendar components:NSCalendarUnitWeekday fromDate:self] weekday];
    LDYDateWeekType type;
    switch (week) {
        case 1:
            type = LDYDateWeekTypeSunday;
            break;
        case 2:
            type = LDYDateWeekTypeMonday;
            break;
        case 3:
            type = LDYDateWeekTypeTuesday;
            break;
        case 4:
            type = LDYDateWeekTypeWednesday;
            break;
        case 5:
            type = LDYDateWeekTypeThursday;
            break;
        case 6:
            type = LDYDateWeekTypeFriday;
            break;
        case 7:
            type = LDYDateWeekTypeSaturday;
            break;
        default:
            break;
    }
    return type;
}

二、判断日期是不是指定的周几:

-(BOOL)ldy_isWeekType:(LDYDateWeekType)type {
    return [self ldy_weekType] == type ?YES:NO;
}

三、返回到指定日期的当年当月当周的周几的日期:

-(NSDate *)ldy_JupmToWeekType:(LDYDateWeekType)targetType {
    LDYDateWeekType currentType = [self ldy_weekType];
    if (currentType == targetType) {
        return self;
    }
    NSInteger interval = targetType - currentType;
    interval = interval>=0 ? interval:-interval;
    return [self ldy_dateByAddingDays:interval];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值