我有以下方法可以帮助我确定当月是否是从月底开始的3天或更短时间:
- (BOOL) checkMonthEnd {
NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *startOfToday;
[cal rangeOfUnit:NSCalendarUnitDay startDate:&startOfToday interval:NULL forDate:now];
NSDate *startOfNextMonth = ({
NSDate *startOfThisMonth;
NSTimeInterval lengthOfThisMonth;
[cal rangeOfUnit:NSCalendarUnitMonth startDate:&startOfThisMonth interval:&lengthOfThisMonth forDate:now];
[startOfThisMonth dateByAddingTimeInterval:lengthOfThisMonth];
});
NSDateComponents *comp = [cal components:NSCalendarUnitDay fromDate:startOfToday toDate:startOfNextMonth options:0];
if (comp.day < 4) {
return YES;
} else {
return NO;
}
}
我想要做的是现在修改它,以便它显示当前日期是否在当前月份开始的前三天内。我怎么能这样做?
答案 0 :(得分:4)
要确定它是否是该月的前三天之一,只需检索NSCalendarUnitDay
并查看它是否小于4:
- (BOOL) checkMonthStart {
NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:NSCalendarUnitDay fromDate:now];
return components.day < 4;
}
顺便说一下,如果你在月底的三天内检查一下你是否会这样做,我可能会建议:
- (BOOL) checkMonthEnd {
NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:NSCalendarUnitDay fromDate:now];
NSRange range = [cal rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:now];
return (range.length - components.day) < 3;
}