如何在NSDate中添加一些周? [英] How to add a number of weeks to an NSDate?
问题描述
我过去使用以下函数在特定时间间隔内使用 NSDateComponents
添加到现有日期。
I have in the past used the below function to add on a specific time interval using NSDateComponents
to an existing date.
(NSDate *)dateByAddingComponents:(NSDateComponents *)comps
toDate:(NSDate *)date
options:(NSCalendarOptions)opts
从iOS8开始, NSDateComponents不推荐使用周值
,这意味着我无法实现我想做的事情:通过在给定的<$中添加一定的周数来生成新的 NSDate
C $ C>的NSDate 。
From iOS8 the week value is deprecated for NSDateComponents
, which means I can't achieve what I want to do: generate a new NSDate
by adding a certain number of weeks to a given NSDate
.
非常感谢任何帮助。
推荐答案
更新:正如Zaph在答案中所说,Apple实际上建议使用 weekOfYear
或 weekOfMonth
而不是我提供的答案。查看Zaph的答案了解详情。
Update: As Zaph said in his answer, Apple actually recommends using weekOfYear
or weekOfMonth
instead of the answer I provided. View Zaph's answer for details.
你可能会很快意识到你正在过度思考它,但是你可以这样做即使周价值已被弃用,也会在某个日期添加一定的周数,例如:
You'll probably quickly realize that you're overthinking it, but here's how you can add a certain number of weeks to a date even though the week value's been deprecated, ex:
NSDateComponents *comp = [NSDateComponents new];
int numberOfDaysInAWeek = 7;
int weeks = 3; // <-- this example adds 3 weeks
comp.day = weeks * numberOfDaysInAWeek;
NSDate *date = [[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:date options:0];
这篇关于如何在NSDate中添加一些周?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!