如何在Objective c中获取当月的日期?

时间:2013-10-30 07:03:54

标签: ios objective-c nsdate nsdatecomponents

我正在开发一个使用日期,月份,年份的应用程序。我想要当前的月份日期,因为当前月份可以有28,29,30,31天。我试图获得当年的月份。但我不知道上面的代码。这是我的代码。

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

2 个答案:

答案 0 :(得分:9)

为了得到一天你可以NSDateComponents

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

您可以根据需要添加更多组件单元:NSMonthCalendarUnit,NSWeekdayCalendarUnit,NSYearCalendarUnit

答案 1 :(得分:7)

可以使用

NSCalendar及其rangeOfUnit:inUnit:forDate方法。 例如,获取当月的天数:

NSCalendar *cal = [NSCalendar currentCalendar];
NSRange range = [cal rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
NSUInteger numberOfDaysInMonth = range.length;