如何计算本周的第一个 NSDate?
即:
NSDate *firstDayOfWeek = [[NSDate date] firstDayOfWeek];
例如,今天是 8 月 19 日,我想从上面的代码行获取 2010-08-15 12:00am
的 NSDate
。谢谢!
i.e.:
NSDate *firstDayOfWeek = [[NSDate date] firstDayOfWeek];
for example, today is Aug 19, I'd want to get a NSDate
of 2010-08-15 12:00am
from above line of code. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我认为该线程响应您正在寻找的内容: http: //www.cocoabuilder.com/archive/cocoa/211648-nsdatecomponents-question.html#211826
但请注意,它不会将星期一处理为一周的第一天,因此您可能需要稍微调整一下通过减去
[gregorian firstWeekday]
而不是仅仅减去1
。另外,我将其修改为使用-currentCalendar
,但这取决于您:-)I think this threads responds to what you're looking for: http://www.cocoabuilder.com/archive/cocoa/211648-nsdatecomponents-question.html#211826
Note however that it doesn't handle Mondays as first days of the week, so you may have to tweek it a little by substracting
[gregorian firstWeekday]
instead of just1
. Also, I modified it to use-currentCalendar
, but it's up to you :-)为什么这么复杂? :)
Why so complicated? :)
如果第一个工作日设置为星期一 (2) 并且您要检查的日期是星期日,则 naixn 的解决方案将产生错误的结果。在这种情况下,您将在下周一得到结果。
正确的方法是按如下方式计算减法部分:
假设您一周总是有 7 天。
The solution by naixn will produce wrong results if monday (2) is set of the firstWeekday and the date you are inspecting is sunday. In this case you will get as a result the monday of next week.
The correct way would be to calculate the subtraction components as follows:
Assuming that you always have 7 days in a week.
这已经得到了回答,但正如 Wolfgang 指出的,接受的答案中有一个错误。如果第一个工作日设置为比相关
NSDate
更大的日期,则结果将不正确。这是一个完整的解决方案,适用于所有可能的firstWeekday
值(示例使用星期一)。This has already been answered, but as Wolfgang has pointed out, there is a bug in the accepted answer. If the first weekday is set as a greater date than the
NSDate
in question, the result will be incorrect. Here is a complete solution that works for all possiblefirstWeekday
values (the example uses Monday).最简单的解决方案:
The simplest solution:
对于斯威夫特 4.1:
For Swift 4.1:
使用 NSDateComponent并将
工作日
设置为1。Use NSDateComponents and set the
weekday
to 1.