设calDate是一个NSDate *类型的变量下面的函数都用其调用
得到现在的日期时间 :
NSDate *now = [NSDate date];
//得到给定日期的那天开始即那天的零点
- (NSDate *)cc_dateByMovingToBeginningOfDay {
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents* parts = [[NSCalendar currentCalendar] components:flags fromDate:self];
[parts setHour:0];
[parts setMinute:0];
[parts setSecond:0];
return [[NSCalendar currentCalendar] dateFromComponents:parts];
}//同理可以写出得到给定日期的那天的结束时间的函数
//得到给定日期所在月份的第一天
- (NSDate *)cc_dateByMovingToFirstDayOfTheMonth {
NSDate *d = nil;
BOOL ok = [[NSCalendar currentCalendar] rangeOfUnit:NSMonthCalendarUnit startDate:&d interval:NULL forDate:self];
NSAssert1(ok, @"Failed to calculate the first day the month based on %@", self);
return d;
}
//得到给定日期所在月份的前一个月份的第一天
- (NSDate *)cc_dateByMovingToFirstDayOfThePreviousMonth {
NSDateComponents *c = [[[NSDateComponents alloc] init] autorelease];
c.month = -1;
return [[[NSCalendar currentCalendar] dateByAddingComponents:c toDate:self options:0] cc_dateByMovingToFirstDayOfTheMonth];
}
//得到给定日期所在月份的天数
- (NSUInteger)cc_numberOfDaysInMonth {
return [[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:self].length;
}