• 【ios】计算两个日期之间相差的年月日


          NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
            [gregorian setFirstWeekday:2];
            NSDate *fromDate = userInfo.birthDay;
            NSDate *toDate = [NSDate date];
            NSDateComponents *components = [gregorian components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0];
            NSInteger year = components.year;
            NSInteger month = components.month;
            NSInteger day = components.day;
            
            if (year > 0) {
                if (month > 0) {
                    strAge = [NSString stringWithFormat:@"%ld岁%ld个月",(long)year,(long)month];
                } else {
                    strAge = [NSString stringWithFormat:@"%ld岁",(long)year];
                }
            } else if (month > 0) {
                if (day > 0) {
                    strAge = [NSString stringWithFormat:@"%ld个月%ld天",(long)month,(long)day];
                } else {
                    strAge = [NSString stringWithFormat:@"%ld个月",(long)month];
                }
            } else {
                if (day >= 0) {
                    strAge = [NSString stringWithFormat:@"%ld天",(long)day];
                }
            }

     计算某人生日,采用这样的方式,可以有效的避免自己算月份的窘态,反正我不说你也知道,那月份存在28 29 30 31多样式变化,有系统API,这么棒的爽感。。。

    你要是想算时分秒,就把NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay 改为

    NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond

    若单纯想只知道两个日期相差多少天,就可以只传递一个NSCalendarUnitDay即可

     

    这个方法有一个bug,怀疑是系统API的问题,即带有31号的月份,31号和30号距离同一个时间的天数是一样的。

    比如说fromDate是2016-3-31,toDate是2016-5-9,那么month=1,day = 9

    而fromDate是2016-3-30,toDate是2016-5-9,那么month=1,day = 9

     

    经过思考,貌似这个解释也是合理的,因为3月有30号、31号,4月只有30号,故而3月30号到4月30号,认为是1个月,3月31号到4月30号,也被认为是一个月。

    每个月天数的不等,导致会有这样的诡异事件出现

     

  • 相关阅读:
    linux最常用命令记录(一)
    2020centos解决“nginx 403 Forbidden"错误的故事
    nginx显示静态html爆502 bad gateway的错误提示
    codeigniter框架的使用感受和注意事项
    网闸
    抗DDOS防火墙
    负载均衡
    上网行为管理
    漏洞扫描系统
    网络分析系统
  • 原文地址:https://www.cnblogs.com/kaysun/p/5466508.html
Copyright © 2020-2023  润新知