Question

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.

Was it helpful?

Solution

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);
}

OTHER TIPS

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];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top