zoukankan      html  css  js  c++  java
  • 【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号,也被认为是一个月。

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

     

  • 相关阅读:
    Android 使用html做UI的方法js与java的相互调用
    WebRequest之HttpWebRequest实现服务器上文件的下载(一)
    使用Json比用string返回数据更友好,也更面向对象一些
    DES加密与解密在GET请求时解密失败的问题解决(终级)
    中大型系统架构组合之EF4.1+ASP.NET MVC+JQuery
    说说标准服务器架构(WWW+Image/CSS/JS+File+DB)
    inline内联函数和宏的区别
    [C语言]mac下Des CBC加密
    x264和FFMPEG 编译后遇到的一些问题:UINT64_C,
    关于多线程的那些事
  • 原文地址:https://www.cnblogs.com/kaysun/p/5466508.html
Copyright © 2011-2022 走看看