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号,也被认为是一个月。

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

     

  • 相关阅读:
    The path "" is not valid path to the gcc binary.
    ADB命令介绍
    Android 中Message,MessageQueue,Looper,Handler详解+实例
    Sqlite 修改字段
    曾经光辉岁月 永远海阔天空
    用AchartEngineActivity引擎自定义图表控件和背景折线图
    一个帖子学会Android开发四大组件
    Android获得系统时间(24小时制)
    TagBuilder
    MVC
  • 原文地址:https://www.cnblogs.com/kaysun/p/5466508.html
Copyright © 2011-2022 走看看