《Flutter入门》flutter计算最近1个月、3个月、半年、12个月

产品需求:获取最近1个月、3个月、半年、1年的交易记录。
最快方式:直接用个30天、60天、180天、365天的Duration,用DateTime相见即可。
存在问题:实际上是不准确的,例如3月1号的最近1个月,应该是2月1-3月1,但是2月如果只有28天,会算成1月30号开始;
优化目标

  • 往前X个月,需要根据前X个月每个月天数相加为准,不是一成不变的30*n;
  • 如往前X个月没有当前天则返回前x月+1个月的1号(例如3月30往前1个月,没有2月30,则返回3月1号)

百度了下没有现成的,自己写了下,给大家参考参考吧。上代码:

  ///计算某个时间往前X个月的具体日期
  ///beforeMonth  月数 例如1、3、5、12(1年)、36(3年)
  ///anchorDateTime 锚定日期,比如2022-7-6
  ///如往前X个月没有有当前天则返回前x月+1个月的1号(例如3月30往前1个月,没有2月30,则返回3月1号)
  static int getBeforeMonthTotalDays(int beforeMonth, DateTime anchorDateTime) {
    DateTime startTime;
    //1--先计算目标年月
    if (anchorDateTime.month <= beforeMonth) {//月份不足,计算年份
      int year = anchorDateTime.year - beforeMonth ~/ 12; //计算年数
      int month =beforeMonth ~/ 12 * 12 + anchorDateTime.month - beforeMonth; //计算月份
      if (month == 0) {//0月改为上一年的12月
        year  -=1;
        month = 12;
      }
      startTime = DateTime(year, month);
    } else {//月份足,直接计算月份
      startTime =
          DateTime(anchorDateTime.year, anchorDateTime.month - beforeMonth);
    }
    //2--计算那个月有多少天,根据该1号和次月1号相差得出
    int totalDays = 0;
    totalDays = startTime.month == 12
        ? DateTime(startTime.year + 1, 1, 1).difference(startTime).inDays
        : DateTime(startTime.year, startTime.month + 1, 1)
            .difference(startTime)
            .inDays;

    //3--计算目标日,根据目标月是否含有目标日,如果没有则返回次月1号
    if (totalDays >= anchorDateTime.day) {// print("该月天数有当前天,直接返回那天");
      //开始日期那个月有那一天
      startTime = DateTime(startTime.year, startTime.month, anchorDateTime.day);
    } else { // print("该月天数没有当前天,返回该月次月1号");
      //没有那一天,则变成次月1号
      if (startTime.month == 12) {//12月,改成次年1月1日
        startTime = DateTime(startTime.year + 1, 1, 1);
      } else { //其他月份直接+1
        startTime = DateTime(startTime.year, startTime.month + 1, 1);
      }
    }
    print(
        "$anchorDateTime 的最近$beforeMonth个月的开始时间为$startTime,总间隔天数${anchorDateTime.difference(startTime).inDays}");
    return anchorDateTime.difference(startTime).inDays;
  }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值