首页 > 代码库 > ios 得到每周的星期一开始和星期天结束的日期
ios 得到每周的星期一开始和星期天结束的日期
得到每周 星期一零点(即本周的开始) 和星期天 24 点(即本周的结束和下一周的开始)的时间
NSDate *now = [NSDate date];NSCalendar *calendar = [NSCalendar currentCalendar];NSDateComponents *comp = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit|NSDayCalendarUnit fromDate:now]; // 得到星期几// 1(星期天) 2(星期二) 3(星期三) 4(星期四) 5(星期五) 6(星期六) 7(星期天)NSInteger weekDay = [comp weekday];// 得到几号NSInteger day = [comp day];NSLog(@"weekDay:%ld day:%ld",weekDay,day); // 计算当前日期和这周的星期一和星期天差的天数long firstDiff,lastDiff;if (weekDay == 1) { firstDiff = 1; lastDiff = 0;}else{ firstDiff = [calendar firstWeekday] - weekDay; lastDiff = 9 - weekDay;}NSLog(@"firstDiff:%ld lastDiff:%ld",firstDiff,lastDiff); // 在当前日期(去掉了时分秒)基础上加上差的天数NSDateComponents *firstDayComp = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];[firstDayComp setDay:day + firstDiff];NSDate *firstDayOfWeek= [calendar dateFromComponents:firstDayComp];NSDateComponents *lastDayComp = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];[lastDayComp setDay:day + lastDiff];NSDate *lastDayOfWeek= [calendar dateFromComponents:lastDayComp];NSDateFormatter *formater = [[NSDateFormatter alloc] init];[formater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];NSLog(@"星期一开始 %@",[formater stringFromDate:firstDayOfWeek]);NSLog(@"当前 %@",[formater stringFromDate:now]);NSLog(@"星期天结束 %@",[formater stringFromDate:lastDayOfWeek]);
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。