2 NSDateComponents - 是同一周吗?
我有一个带有 BOOL 返回值和 2 个输入 (NSDateComponents *) 参数的函数。 我的问题是我有两个 NSDateComponents 值,我想知道这两个日期是否在同一日历周内。我尝试了最简单的解决方案来解决问题,我的想法如下:
- (BOOL)isFunctionName:(NSDateComponents *)comp1 和Param:(NSDateComponents *)comp2 { return (([comp1 周] == [comp2 周]) && ([comp1 年] == [comp2 年])); }
但这是不正确的。 我可以用什么方法解决它?
编辑
后,我有一个函数可以从日期中生成日期组件。
<代码> -(NSDateComponents *)dateToDateComponents:(NSDate *)日期 { 无符号的unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *dateComponents = [公历组件:unitFlags fromDate:date]; [公历发布]; 返回日期组件; }
我这样称呼它:
if ([self isFunctionName: [self dateToDateComponents:startDate] 和 Param:[self dateToDateComponents:currentTripDate]]){ }
在我的测试过程中,它返回 YES 我的所有日期(例如 2010.07.21 - 2010.08.18)
i have got a function with BOOL return value and 2 input (NSDateComponents *) parameters.
My trouble is I have two NSDateComponents values and I want to know if the two date fall within the same calendar week. i tried the simplest solutions to solve problem, my idea was the following:
- (BOOL)isFunctionName:(NSDateComponents *)comp1 andParam:(NSDateComponents *)comp2 {
return (([comp1 week] == [comp2 week]) && ([comp1 year] == [comp2 year]));
}
but it's not correct.
what way i can solve it ?
edited
so i have a function which makes datecomponents from dates.
-(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;
}
and i call it this way:
if ([self isFunctionName: [self dateToDateComponents:startDate] and Param:[self dateToDateComponents:currentTripDate]]){
}
and during my test it returns YES all of my dates (for example 2010.07.21 - 2010.08.18)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是受到罗伯特回答的启发。我对其进行了一些调整,以解决一周跨越两年的问题,例如 12/31/2012 和 2012 年 12 月 31 日。 2013 年 1 月 1 日。
This is inspired by Robert's answer. I tweaked it a bit to address the issue when a week crosses two years, e.g. 12/31/2012 & 1/1/2013.
NSDateComponent 类参考指出:
比较
NSDate
怎么样?编辑:
在这一行中:
您没有传递
NSWeekCalendarUnit
,因此[dateComponent week]
返回NSUndefinedDateComponent
edit
当然,它必须是
NSWeekCalendarUnit
...The NSDateComponent class reference states:
What about comparing
NSDate
s instead?edit:
In this line:
You don't pass
NSWeekCalendarUnit
, therefore[dateComponent week]
returnsNSUndefinedDateComponent
edit
Of course, it has to be
NSWeekCalendarUnit
…从 iOS8 开始,这变得更加容易:
从 文档:
Starting from iOS8, this became much easier:
From the documentation: