iOS 获取一周的时间,周一到周日的日期

2017-08-03  本文已影响891人  ShineYangGod

//获取一周的日期
-(NSArray *)adddDataOnViews
{
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;
// weekDay = 1;
if (weekDay == 1)
{
firstDiff = -6;
lastDiff = 0;
}
else
{
firstDiff = [calendar firstWeekday] - weekDay + 1;
lastDiff = 8 - weekDay;
}
// NSLog(@"firstDiff: %ld lastDiff: %ld",firstDiff,lastDiff);
// 在当前日期(去掉时分秒)基础上加上差的天
NSDateComponents *firstDayComp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:nowDate];
[firstDayComp setDay:day + firstDiff];
NSDate *firstDayOfWeek = [calendar dateFromComponents:firstDayComp];
NSDateComponents *lastDayComp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:nowDate];
[lastDayComp setDay:day + lastDiff];
NSDate *lastDayOfWeek = [calendar dateFromComponents:lastDayComp];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd"];
NSString *firstDay = [formatter stringFromDate:firstDayOfWeek];
NSString *lastDay = [formatter stringFromDate:lastDayOfWeek];
NSLog(@"%@=======%@",firstDay,lastDay);

int firstValue = firstDay.intValue;
int lastValue = lastDay.intValue;

NSMutableArray *dateArr = [[NSMutableArray alloc]init];
if (firstValue < lastValue) {
    
    for (int j = 0; j<7; j++) {
        NSString *obj = [NSString stringWithFormat:@"%d",firstValue+j];
        [dateArr addObject:obj];
    }
}
else if (firstValue > lastValue)
{
    for (int j = 0; j < 7-lastValue; j++) {
        NSString *obj = [NSString stringWithFormat:@"%d",firstValue+j];
        [dateArr addObject:obj];
    }
    for (int z = 0; z<lastValue; z++) {

        NSString *obj = [NSString stringWithFormat:@"%d",z+1];
        [dateArr addObject:obj];
    }
}
return dateArr;

}

上一篇下一篇

猜你喜欢

热点阅读