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
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
.
Any help would be greatly appreciated.
Update: As Zaph said in his answer, Apple actually recommends using
weekOfYear
orweekOfMonth
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:
I prefer to use dateByAddingUnit. It's more intuitive
Just use
weekOfYear
:Apple docs for
NSDateComponents
week
:Output:
If you use
week
you get this warning:When using the
weekOfMonth
orweekOfYear
as a delta they work the same. Where they are different is when they are used to obtain the week number where you will get the week of the month with a range of 6 or the week of the year with a range of 53.You can add a category on NSDate with the following method: