一些与日历,日期有关的用法

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








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值