如何计算两个日期之间的差异并在颤动中获取年月日

how to calculate difference between two date and get year month and days in flutter

如何在 dart 中更改日期格式

我得到从和到现在的差值是整数。如何将此整数更改为日期格式...并将其转换为 0Days 0Months 7days; I need this type of format

but I got this type of format 查看车龄:

 vehicleAge(DateTime doPurchase, DateTime doRenewel) {
    age = doPurchase.difference(doRenewel).abs().inDays.toInt();
    return age;
  }

这是我的职责...

试试这个

 vehicleAge(DateTime doPurchase, DateTime doRenewel) {
    Duration parse = doPurchase.difference(doRenewel).abs();
    return "${parse.inDays~/360} Years ${((parse.inDays%360)~/30)} Month ${(parse.inDays%360)%30} Days";
  }

使用这个包 time_machine 并尝试这个代码

 vehicleAge(DateTime doPurchase, DateTime doRenewel) {

  LocalDate a = LocalDate.dateTime(doPurchase);
  LocalDate b = LocalDate.dateTime(doRenewel);
  
  Period diff = b.periodSince(a);
  return "${diff.years} Years ${diff.months} Months ${diff.days} Days";
}

正确答案

我答对了use jiffy package

import 'package:jiffy/jiffy.dart';

然后使用此代码

vehicleAge(DateTime doPurchase, DateTime doRenewel) {
    var dt1 = Jiffy(doPurchase);
    var dt2 = Jiffy(doRenewel);

    int years = int.parse("${dt2.diff(dt1, Units.YEAR)}");
    dt1.add(years: years);

    int month = int.parse("${dt2.diff(dt1, Units.MONTH)}");
    dt1.add(months: month);

    var days = dt2.diff(dt1, Units.DAY);

    
    return "$years Years $month Month $days Days";
    
  }