【问题标题】:Getting the number of days of the month in NSDate in Objective-C?在Objective-C的NSDate中获取一个月的天数?
【发布时间】:2014-06-29 10:35:49
【问题描述】:

所以我一直试图在 int 中找到一个月的最后一天,但我使用的代码总是认为最后一天是 30

我使用的代码是这样的

NSDate *curDate = [NSDate date];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* compsd = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:curDate]; // Get necessary date components

    // set last of month
    [compsd setMonth:[compsd month]+1];
    [compsd setDay:0];
    NSDate *tDateMonth = [calendar dateFromComponents:compsd];
    //NSLog(@"%@", tDateMonth);

    //[comps setMonth:[comps month]+1];
    //[comps setDay:0];
   // NSDate *tDateMonth = [cal dateFromComponents:comps];
    //NSLog(@"%@", tDateMonth);
     //*/

    NSString *tDateString = [NSString stringWithFormat:@"%@", tDateMonth];
    NSString *dateNTime = [[tDateString componentsSeparatedByString:@"-"] objectAtIndex:2];
    int justDate = [[[dateNTime componentsSeparatedByString:@" "] objectAtIndex:0] intValue];
    NSLog(@"Last Day of %@ is %d", monthName, justDate);

我错过了什么?

【问题讨论】:

  • 正如@Fry 所表明的那样,花时间研究 API 可以节省编码时间。
  • 您缺少的(除其他外)是对如何使用 NSDateFormatter 的理解。
  • 您使用 NSCalendar 但从未查看文档以找到 rangeOfUnit??

标签: objective-c


【解决方案1】:

试试这个简单的方法:

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

【讨论】:

    【解决方案2】:

    我想你可以试试这样的东西

    NSDate *currentDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:currentDate];
    
    [components setMonth:[components month]+1];
    [components setDay:0];
    NSDate *theDate = [calendar dateFromComponents:components];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"d"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    
    NSString *dateString = [dateFormatter stringFromDate:theDate];
    NSInteger dateInt = [dateString intValue];
    NSLog(@"The int: %i", dateInt);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-25
      相关资源
      最近更新 更多