NSCalendar的使用

I. 获取具体的 年, 月, 日, 时, 分, 秒 元素

    //当前日历
    NSCalendar *calendar = [NSCalendar currentCalendar];

    //获得NSDate每一个元素

    // - component:fromDate:
    // Desc - Returns the specified date component from a given date

    NSInteger year = [calendar component:NSCalendarUnitYear fromDate:[NSDate date]];
    NSInteger month = [calendar component:NSCalendarUnitMonth fromDate:[NSDate date]];
    NSInteger day = [calendar component:NSCalendarUnitDay fromDate:[NSDate date]];
    QMLog(@"year = %zd month = %zd day = %zd", year, month, day);

    //获取NSDate的多个元素

    // - components:fromDate:
    // Desc - Returns a NSDateComponents object containing a given date decomposed into specified components.

    NSDateComponents *cmps = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
    QMLog(@"year = %zd month = %zd day = %zd", cmps.year, cmps.month, cmps.day);

II. 比较两个日期之间相差的时间, 可以单独看到每个元素的差值

    NSCalendar *calendar = [NSCalendar currentCalendar];

    //需要获得的元素枚举
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;

    //相差的时间段

    // - components:fromDate:toDate:options:
    // Desc: Returns, as an NSDateComponents object using specified components, the difference between two supplied dates.

    NSDateComponents *nowCmps = [calendar components:unit fromDate:fromDate toDate:destinationDate options:0];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值