如何获得NSDAte的最后日期?

时间:2010-12-23 10:59:16

标签: iphone

我已经实现了一个iphone应用程序,我希望获得当月的最后日期。 我不知道怎么可能。

请帮我解决这个问题。

提前致谢。

2 个答案:

答案 0 :(得分:3)

另一种可能性:

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

答案 1 :(得分:0)

这应该有效:

#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;
}

结果:

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