iOS 獲取一周的時(shí)間,周一到周日的日期

獲取一周的日期

-(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];
    // 獲取幾天是幾號(hào)
    NSInteger day = [comp day];
    // 計(jì)算當(dāng)前日期和本周的星期一和星期天相差天數(shù)
    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);
    // 在當(dāng)前日期(去掉時(shí)分秒)基礎(chǔ)上加上差的天
    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;

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容