How to get dates of current month in Objective c?

Manimaran picture Manimaran · Oct 30, 2013 · Viewed 9k times · Source

I am developing a app which uses the date, month, year. I want the current month dates,because current month can have 28,29,30,31 days. I have tried to get current year months. but i don't know the code for above. here is my code.

  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate           *today           = [NSDate date];
NSCalendar       *currentCalendar = [NSCalendar currentCalendar];
NSDateComponents *yearComponents  = [currentCalendar components:NSYearCalendarUnit  fromDate:today];
int currentYear  = [yearComponents year];
for(int months = 0; months < 12; months++)
{
    NSString *monthName = [NSString stringWithFormat:@"%@ %i",[[dateFormatter monthSymbols]objectAtIndex: months],currentYear];
    NSLog(@"%@ %i",[[dateFormatter monthSymbols]objectAtIndex: months],currentYear);
    [monthArray addObject:monthName];
}

Answer

Jay Gajjar picture Jay Gajjar · Oct 30, 2013

To get day you can you NSDateComponents

NSDate *date = [NSDate date];
NSCalendar *gregorian = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit) fromDate:date];
NSInteger day = [dateComponents day];

You can add more component units as you need like :NSMonthCalendarUnit,NSWeekdayCalendarUnit,NSYearCalendarUnit