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];
}
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
NSCalendar
and its rangeOfUnit:inUnit:forDate
method can be use.
For eg., to get the number of days in the current month:
NSCalendar *cal = [NSCalendar currentCalendar];
NSRange range = [cal rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
NSUInteger numberOfDaysInMonth = range.length;
来源:https://stackoverflow.com/questions/19675848/how-to-get-dates-of-current-month-in-objective-c