Alex Rivera | Logout

Get firstdate, lastdate of month?

Asked 2012-05-23T09:57:45.933
17

I want to get firstdate、lastdate of month,I try

NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
[components setDay:1];
self.currentDate = [calendar dateFromComponents:components];
int m = components.month;
int y = components.year;
int d = components.day;

log: 2012,5,1

How can i get lastdate od month?

please give me some advice,thank you!!

Edit
Report

2 Answers

3

Ok, since I'm rolling my own calendar control, I went ahead and created a NSCalendar category. Here's my lastOfMonth method:

- (NSDate *)lastOfMonth:(NSDate *)date
{
    NSDateComponents *dc = [self components:NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit fromDate:date];

    NSRange dim = [self rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
    dc.day = dim.length;

    return [self dateFromComponents:dc];
}
answered 2013-06-24T19:06:40.990
1

You can get last date of month using :-

NSDate currDate=[NSDate date];

-(NSString *)getLastDateMonth:(NSDate *)currDate{

  NSCalendar *gregCalendar=[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

  NSDateComponents *components=[gregCalendar components:NSMonthCalendarUnit|NSYearCalendarUnit fromDate:currDate];
  NSInteger month=[components month];
  NSInteger year=[components year];

  if (month==12) {
    [components setYear:year+1];
    [components setMonth:1];
  } else {
    [components setMonth:month+1];
  }
  [components setDay:1];

  NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
  [dateFormat setDateStyle:NSDateFormatterShortStyle];
  NSString *lastDateOfMonth = [dateFormat stringFromDate:(NSDate *)[[gregCalendar dateFromComponents:components] dateByAddingTimeInterval:-86400]];
  dateFormat=nil;
  return lastDateOfMonth;
}
answered 2012-05-23T09:59:48.180

Your Answer