I have implemented one iphone application in which i want to get last date of current month. I don't know how it possible.
Please help m开发者_如何学运维e for this question.
Thanks in advance.
another possibility:
NSRange daysRange = [[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
NSDateComponents *comp = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date];
[comp setDay:daysRange.length];
NSDate *endOfMonth = [[NSCalendar currentCalendar] dateFromComponents:comp];
This ought to work:
#import <Foundation/Foundation.h>
NSDate *lastOfMonth(NSDate *today)
{
// get a gregorian calendar
NSCalendar *calendar=[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
// get current month and year
NSDateComponents *components=[calendar components:NSMonthCalendarUnit|NSYearCalendarUnit fromDate:today];
NSInteger month=[components month];
NSInteger year=[components year];
// set components to first day of next month
if (month==12) {
[components setYear:year+1];
[components setMonth:1];
}
else {
[components setMonth:month+1];
}
[components setDay:1];
// get last day of this month by subtracting 1 day (86400 seconds) from first of next
return [[calendar dateFromComponents:components] dateByAddingTimeInterval:-86400];
}
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// the date tocay
NSDate *today=[NSDate date];
NSLog(@"today: %@", today);
NSLog(@"last of month: %@", lastOfMonth(today));
[pool drain];
return 0;
}
result:
2010-12-23 11:20:36.499 so[46812:a0f] today: 2010-12-23 11:20:36 +0000
2010-12-23 11:20:36.501 so[46812:a0f] last of month: 2010-12-31 00:00:00 +0000
精彩评论