获取当前月 / 获取当前年 ++ --

#pragma mark - 获取当前月

- (NSString *)getMonth

{

NSDate *nowDate = [NSDate date];

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *comp = [calendar components: NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitDay fromDate:nowDate];

// 获取今天是周几

NSInteger weekDay = [comp weekday];

// 获取今天是几号

NSInteger day = [comp day];

// 获取今天是几月

NSInteger month = [comp month];

// 计算当前日期和本周的星期一和星期天相差天数

long firstDiff,lastDiff;

if (weekDay == 1)

{

firstDiff = -31;

lastDiff = 0;

if (_NumM > 1) {

firstDiff = [calendar firstWeekday] - weekDay + 1 - ((_NumM)*31);

lastDiff = 31 - weekDay;

}

}

else

{

if(_NumM == 0)

{

firstDiff = [calendar firstWeekday] - weekDay + 1;

lastDiff = 31 - weekDay;

}else

{

firstDiff = [calendar firstWeekday] - weekDay + 1 - ((_NumM -1)*31);

lastDiff = 31 - weekDay;

}

}

NSDateComponents *firstDayComp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay  fromDate:nowDate];

[firstDayComp setDay:day + firstDiff];

NSDate *firstDayOfWeek = [calendar dateFromComponents:firstDayComp];

DLog(@"firstDayOfWeek: %@",firstDayOfWeek);

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setDateFormat:@"yyyy-MM"];

// 本周第一天时间

NSString *firstDay = [formatter stringFromDate:firstDayOfWeek];

return firstDay;

}



#pragma mark - 获取当前年

-(NSString *)getYear{

NSDate *nowDate = [NSDate date];

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *comp = [calendar components: NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitDay fromDate:nowDate];

// 获取今天是周几

NSInteger weekDay = [comp weekday];

// 获取几天是几号

NSInteger day = [comp day];

// 计算当前日期和本周的星期一和星期天相差天数

long firstDiff,lastDiff;

if (weekDay == 1)

{

firstDiff = -364;

lastDiff = 0;

if (_NumY > 1) {

firstDiff = [calendar firstWeekday] - weekDay + 1 - ((_NumY -1)*365);

lastDiff = 365 - weekDay;

}

}

else

{

if(_NumY == 0)

{

firstDiff = [calendar minimumDaysInFirstWeek] - weekDay + 1;

lastDiff = 365 - weekDay;

}else

{

firstDiff = [calendar minimumDaysInFirstWeek] - weekDay + 1 - ((_NumY -1)*365);

lastDiff = 365 - weekDay;

}

}

NSDateComponents *firstDayComp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay  fromDate:nowDate];

[firstDayComp setDay:day + firstDiff];

NSDate *firstDayOfWeek = [calendar dateFromComponents:firstDayComp];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setDateFormat:@"yyyy"];

// 本周第一天时间

NSString *firstDay = [formatter stringFromDate:firstDayOfWeek];

// 本周最后一天时间

//    NSString *lastDay = [formatter stringFromDate:lastDayOfWeek];

return firstDay;

}

你可能感兴趣的:(获取当前月 / 获取当前年 ++ --)