1

I am looking for a way to get a list of the last six months from today.

Today is in May so I would be looking for an output of:

May 2013,
Apr 2013,
Mar 2013,
Feb 2013,
Jan 2013,
Dec 2012

I understand it will have something to do with NSDateComponents, but I can't find any help on this one.

jscs
  • 63,694
  • 13
  • 151
  • 195

2 Answers2

2

Try this, you can change the value of int i as per your choice

NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];

for (int i = 0; i <=6 ;i++) {
    [offsetComponents setMonth:-i];

    NSDate *dateStr = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMMM YYYY"];
    NSString *stringFromDate = [formatter stringFromDate:dateStr];
    NSLog(@"%@", stringFromDate);
}
Deepesh Gairola
  • 1,252
  • 12
  • 18
  • Perfect thanks! I actually solved it with a similar route, came back here to update my post and I already had answers. Much appreciated! – Andrew A. Barber May 16 '13 at 12:21
  • The performance of this is could be dramatically improved by moving the the `formatter` creation and setup to outside the `for` loop. The creation of the formatter is a large performance overhead so you should try to re-use where possible – jr19 Jan 25 '14 at 09:40
1

I would suggest to use MTDates with something like:

[[NSDate date] mt_dateMonthsBefore:1];
[[NSDate date] mt_dateMonthsBefore:2];
[[NSDate date] mt_dateMonthsBefore:3];
[[NSDate date] mt_dateMonthsBefore:4];
[[NSDate date] mt_dateMonthsBefore:5];
[[NSDate date] mt_dateMonthsBefore:6];
zlajo
  • 2,173
  • 1
  • 19
  • 25