0

So i've been trying to find the last day of the month in an int but the code I'm using always thinks the last day is 30

Last Day is January

the code i am using looks like this

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);

What am I missing?

new2ios
  • 1,350
  • 2
  • 25
  • 56
inVINCEable
  • 2,167
  • 3
  • 25
  • 49
  • possible duplicate of [Number of days in the current month using iPhone SDK?](http://stackoverflow.com/questions/1179945/number-of-days-in-the-current-month-using-iphone-sdk) – Marek R Jun 29 '14 at 10:42
  • 1
    As @Fry has shown spending the time researching the APIs can save coding time. – zaph Jun 29 '14 at 10:43
  • What you're missing (among other things) is an understanding of how to use NSDateFormatter. – Hot Licks Jun 29 '14 at 12:04
  • You use NSCalendar but never looked at the documentation to find `rangeOfUnit`?? – Hot Licks Jun 29 '14 at 12:06

2 Answers2

4

Try this simple way:

NSCalendar *cal = [NSCalendar currentCalendar];
NSRange rng = [cal rangeOfUnit:NSDayCalendarUnit 
                        inUnit:NSMonthCalendarUnit
                       forDate:[NSDate date]];
NSUInteger numberOfDaysInMonth = rng.length;
Fry
  • 6,235
  • 8
  • 54
  • 93
0

I guess you can try something like this

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);