下面是我在工作中使用的計算某個日期與當前日期比較是否在同一周內(nèi)渡八,我現(xiàn)在感覺有點麻煩迂求,不知道還有沒有簡單的方法默伍,如果有歡迎給我留言欢嘿,馬上改正。
- (BOOL) isSameWeekWithDate:(NSDate *)date {
NSCalendar *calendar = [NSCalendar currentCalendar];
int unit = NSCalendarUnitWeekday | NSCalendarUnitMonth | NSCalendarUnitYear | kCFCalendarUnitDay | kCFCalendarUnitHour | kCFCalendarUnitMinute ;
//1.獲得當前時間的 年月日
NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];
NSDateComponents *sourceCmps = [calendar components:unit fromDate:date];
// 對比時間差
NSDateComponents *dateCom = [calendar components:unit fromDate:[NSDate date] toDate:date options:0];
NSInteger subDay = labs(dateCom.day);
NSInteger subMonth = labs(dateCom.month);
NSInteger subYear = labs(dateCom.year);
if (subYear == 0 && subMonth == 0) { //當相關的差值等于零的時候說明在一個年也糊、月炼蹦、日的時間范圍內(nèi),不是按照零點到零點的時間算的
if (subDay > 6) { //相差天數(shù)大于6肯定不在一周內(nèi)
return NO;
} else { //相差的天數(shù)大于或等于后面的時間所對應的weekday則不在一周內(nèi)
if (dateCom.day >= 0 && dateCom.hour >=0 && dateCom.minute >= 0) { //比較的時間大于當前時間
//西方一周的開始是從周日開始算的狸剃,周日是1掐隐,周一是2,而我們是從周一開始算新的一周
NSInteger chinaWeekday = sourceCmps.weekday == 1 ? 7 : sourceCmps.weekday - 1;
if (subDay >= chinaWeekday) {
return NO;
} else {
return YES;
}
} else {
NSInteger chinaWeekday = sourceCmps.weekday == 1 ? 7 : nowCmps.weekday - 1;
if (subDay >= chinaWeekday) { //比較的時間比當前時間小钞馁,已經(jīng)過去的時間
return NO;
} else {
return YES;
}
}
}
} else { //時間范圍差值超過了一年或一個月的時間范圍肯定就不在一個周內(nèi)了
return NO;
}
}
在網(wǎng)上看到有人只是比較了一下year虑省、month、day僧凰,說是在同一周內(nèi)了探颈,我測了一下并不能返回正確的結(jié)果,代碼如下:
return (selfCmps.year == nowCmps.year) && (selfCmps.month == nowCmps.month) && (selfCmps.day == nowCmps.day);
}