2

How do you show how much time has elapsed since from example 16 May 2023? In years, months, weeks, days, hours, minutes and seconds? The idea is that after 4 weeks it would show 1 month and 0 weeks. Thanks

1 Answers1

0

Here's a simple function to find the days in between dates:

int daysBetween(DateTime from, DateTime to) {
   from = DateTime(from.year, from.month, from.day);
   to = DateTime(to.year, to.month, to.day);
   return (to.difference(from).inHours / 24).round();
}

final date1 = DateTime(2023, 5, 16);
final date2 = DateTime.now();
final difference = daysBetween(date1, date2);

Then you want to convert the days to it's most optimal units. This can be done by checking if it's over a threshold (for example 7 days) then dividing it by the threshold to convert days to that unit.

For example, if you want to convert days into weeks:

if (numberOfDays >= 7) {
  numberOfWeeks = numberOfDays / 7;
}

You can then chain this with months, years, etc. :

if (numberOfDays >= 365.25) {
  numberOfYears = (numberOfDays / 365.25).round();
  numberOfDays = numberOfDays - (numberOfYears * 365.25);
}

if (numberOfDays >= 30.437) {
  numberOfMonths = (numberOfDays / 30.437).round();
  numberOfDays = numberOfDays - (numberOfMonths * 30.437);
}

if (numberOfDays >= 7) {
  numberOfWeeks = (numberOfDays / 7).round();
  numberOfDays = numberOfDays - (numberOfWeeks * 7);
}

final differenceWithUnits = DateTime(numberOfYears, numberOfMonths, (numberOfWeeks * 7) + numberOfDays)

365.25 is the average number of days in a year, 30.437 is the average number of days in a month, and 7 is obviously the average number of days in a week.

In the differenceWithUnits, it only takes years, months, and days, so I converted weeks & days into just days.

Hope this helps!

I got the first part from: https://stackoverflow.com/a/52713358/16098405

Aaron Chauhan
  • 15
  • 1
  • 6