0

Consider a start date and an end date:

NSDate *startDate, *endDate;

For example, startDate could be Dec 10, 2010 and endDate could be Jan 4, 2011.

Consider the span of days from Dec 10, 2010 to Jan 4, 2011.

How could I determine the date range over that same span of days but exactly 1 year ago. And I'd like it to take into consideration leap years. So I'm unable to simply subtract 365 days from each date.

I'd like to end up with:

NSDate *oneYearAgoStartDate, *oneYearAgoEndDate.

So maybe in this case, oneYearAgoStartDate would be Dec 10, 2009 and oneYearAgoEndDate would be Jan 4, 2010 (note that I haven't confirmed this).

How could I initialize these two variables to achieve what I need.

CodeGuy
  • 28,427
  • 76
  • 200
  • 317
  • 2
    Check if [NSDate subtract period](http://stackoverflow.com/questions/4611390/nsdate-substract-one-month/4611496#4611496) answers your question, with minimal adaptation (replacing `setMonth` by `setYear`). – jweyrich Jan 15 '11 at 23:26

1 Answers1

6

I'd say you want to take a look at NSCalendar, specifically the method -dateByAddingComponents:toDate:options:. In your instance, the NSDataComponents instance would have a year of -1.

Sixten Otto
  • 14,816
  • 3
  • 48
  • 60