0

我正在尝试计算当月的天数

      today = [NSDate date];

    NSLog(@"%@", today);

    //calculate how much days in current month

    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSRange days = [cal rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:today];
    NSUInteger numberOfDaysInMonth = days.length;

    NSLog(@"%d Days in month:%i", numberOfDaysInMonth, NSMonthCalendarUnit);

   // end calculating

在日志中它显示八月而不是五月

为什么会发生?我错过了什么?

谢谢

2013-05-07 21:39:01.344 NsTimer[89023:c07] 2013-05-07 18:39:01 +0000 2013-05-07 21:39:01.345 NsTimer[89023:c07] 31 天:8

回答:

谢谢@artur

这是一个正确的代码

    today = [NSDate date];

    NSLog(@"%@", today);

    //calculate how much days in current month

    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    int units = NSMonthCalendarUnit;
    NSDateComponents *comps = [cal components:units fromDate:today];
    NSRange days = [cal rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:today];
    NSUInteger numberOfDaysInMonth = days.length;

    NSLog(@"%d Days in month:%i", numberOfDaysInMonth, comps.month);

   // end calculating

日志现在显示:

2013-05-07 22:25:04.855 NsTimer[89623:c07] 2013-05-07 19:25:04 +0000
2013-05-07 22:25:04.856 NsTimer[89623:c07] 31 Days in month:5
4

1 回答 1

1

NSMonthCalendarUnit以整数 ( %i) 形式记录。它只是枚举标志值,意外为 8。要显示月份数,您应该使用[[calendar components:NSMonthCalendarUnit fromDate:today] month].

于 2013-05-07T18:49:15.440 回答