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

How can I change Date formate in dart

I get the from and to date difference value is int. How to change this integer to date format... and convert it to 0Days 0Months 7days; I need this type of format

but I got this type of format see the Vehicle Age:

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

That is my function...



Solution 1:[1]

Use this package time_machine and try this code

 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";
}

Solution 2:[2]

Try with this

 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";
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2