计算“上周五”带 NSDate + NSDate组件
我在使用 NSDate 和 NSDateComponents 计算相对于当前日期的特定日期时遇到一些问题。例如,假设我想要上周五。我尝试了以下操作:
NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit) fromDate:[NSDate date]];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
[components setWeekday:6]; //Friday
[components setWeek:[components week] - 1]; //Last Week
return [[NSCalendar currentCalendar] dateFromComponents:components];
但这只是返回当前日期,好像它无法弄清楚我要的是什么。
这感觉应该很简单,但我只是没有让它发挥作用。有什么指点吗?
I'm having some trouble computing specific days relative to the current date using NSDate and NSDateComponents. For example, let's say I want last Friday. I tried the following:
NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit) fromDate:[NSDate date]];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
[components setWeekday:6]; //Friday
[components setWeek:[components week] - 1]; //Last Week
return [[NSCalendar currentCalendar] dateFromComponents:components];
But that just returns the current date, as if it can't figure out what I'm asking for.
This feels like it should be simple enough but I'm just not getting it working. Any pointers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像这样的事情怎么样:
How about something like this:
使用此代码:
Use this code:
我写了这个函数:
当你寻找星期日时,
weekdayNumber
是 1。 2 周一。如果您想查找 10 月的最后一个星期五,可以使用以下命令:
其中日期是 2016 年 10 月 11 日或 10 月的任何其他一天。
I wrote this function:
weekdayNumber
is 1 when you are looking for Sunday. 2 for Monday.If you want to find last Friday in October you can use this:
where date is let's say the 11th of October, 2016 or any other day of October.