我有一个具有BOOL返回值和2个输入(NSDateComponents *)参数的函数。 我的麻烦是我有两个NSDateComponents值,我想知道这两个日期是否属于同一日历周。我尝试了最简单的解决问题的解决方案,我的想法如下:
- (BOOL)isFunctionName:(NSDateComponents *)comp1 andParam:(NSDateComponents *)comp2 {
return (([comp1 week] == [comp2 week]) && ([comp1 year] == [comp2 year]));
}
但这不正确。 我能以什么方式解决它?
编辑
所以我有一个从日期开始生成日期组件的功能。
-(NSDateComponents *)dateToDateComponents:(NSDate *)date {
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:unitFlags fromDate:date];
[gregorian release];
return dateComponents;
}
我用这种方式称呼它:
if ([self isFunctionName: [self dateToDateComponents:startDate] and Param:[self dateToDateComponents:currentTripDate]]){
}
在我的测试期间,我的所有日期都返回YES(例如2010.07.21 - 2010.08.18)
答案 0 :(得分:2)
这是受罗伯特回答的启发。当一周过了两年时,我稍微调整一下来解决这个问题,例如: 12/31/2012& 2013年1月1日。
- (BOOL)isOnSameWeekAsDate:(NSDate*)otherDate
{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
unsigned unitFlags = NSCalendarUnitYearForWeekOfYear | NSCalendarUnitWeekOfYear;
NSDateComponents *components = [calendar components:unitFlags fromDate:self];
NSDateComponents *otherComponents = [calendar components:unitFlags fromDate:otherDate];
return ( [components yearForWeekOfYear] == [otherComponents yearForWeekOfYear] && [components weekOfYear] == [otherComponents weekOfYear] );
}
答案 1 :(得分:1)
NSDateComponent类引用声明:
重要提示:
NSDateComponents
对象本身毫无意义;您 需要知道它是什么日历 解释,你需要 知道这些值是否绝对 单位的价值或数量 单位。
如果要比较NSDate
呢?
- (BOOL) weekIsEqual:(NSDate *)date and:(NSDate *)otherDate {
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *dateComponents = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit fromDate:date];
NSDateComponents *otherDateComponents = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit fromDate:otherDate];
return [dateComponents week] == [otherDateComponents week] && [dateComponents year] == [otherDateComponents year];
}
修改强>: 在这一行:
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
您未通过NSWeekCalendarUnit
,因此[dateComponent week]
会返回NSUndefinedDateComponent
修改强>
当然,它必须是NSWeekCalendarUnit
...
答案 2 :(得分:0)
从iOS8开始,这变得更加容易:
-(BOOL)isDate:(NSDate *)date1 onSameWeekAs:(NSDate *)date2
{
return [[NSCalendar currentCalendar] isDate:date1
equalToDate:date2
toUnitGranularity:NSCalendarUnitWeekOfYear];
}
如果两个日期对于所有单位具有相同的日期成分,则返回YES 大于或等于给定单位,否则为NO。