Jason Jason - 2 years ago 81
Objective-C Question

How to get all the date of last one month

i want to get all the dates from yesterday date to one month..
like today is 19 may, so i need all the date from 18 may to 18 April.
please help.
how to get all the date of last one month?

Answer Source

You can use this code.It works.

NSDate *currentDate = [NSDate date];
NSLog(@"Current Date = %@", currentDate);

NSDateComponents *dateComponents = [NSDateComponents new];
dateComponents.month = -1;

NSDate *currentDatePlus1Month = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:currentDate options:0];

NSLog(@"Date = %@", currentDatePlus1Month );

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *days = [[NSDateComponents alloc] init];
NSMutableArray* arr =[[NSMutableArray alloc]init];
NSInteger dayCount = 0;
while ( TRUE ) {
    [days setDay: ++dayCount];
    NSDate *date = [gregorianCalendar dateByAddingComponents: days toDate: currentDatePlus1Month options: 0];
    if ( [date compare: currentDate] == NSOrderedAscending ){
        [arr addObject:date];

    if([[arr lastObject] isEqual:[currentDate dateByAddingTimeInterval:-60*60*24*1]])
        NSLog(@"%lu",(unsigned long)arr.count);

    // Do something with date like add it to an array, etc.

if you find all dates you can remove count and get all dates in array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download