Question

Converting DateTime to time ago in Dart/Flutter

The question is how to format a Dart DateTime as a string stating the time elapsed similar to the way you see times displayed on Stack Overflow.

Is there any better method than this

String timeAgo(DateTime d) {
 Duration diff = DateTime.now().difference(d);
 if (diff.inDays > 365)
  return "${(diff.inDays / 365).floor()} ${(diff.inDays / 365).floor() == 1 ? "year" : "years"} ago";
 if (diff.inDays > 30)
  return "${(diff.inDays / 30).floor()} ${(diff.inDays / 30).floor() == 1 ? "month" : "months"} ago";
 if (diff.inDays > 7)
  return "${(diff.inDays / 7).floor()} ${(diff.inDays / 7).floor() == 1 ? "week" : "weeks"} ago";
 if (diff.inDays > 0)
  return "${diff.inDays} ${diff.inDays == 1 ? "day" : "days"} ago";
 if (diff.inHours > 0)
  return "${diff.inHours} ${diff.inHours == 1 ? "hour" : "hours"} ago";
 if (diff.inMinutes > 0)
  return "${diff.inMinutes} ${diff.inMinutes == 1 ? "minute" : "minutes"} ago";
 return "just now";
}

Thank you and hope it helps others

 46  40730  46
1 Jan 1970

Solution

 51

I used timeago for the exact purpose and found it quite useful. It has multiple format and different languages support as well.

2019-01-16

Solution

 18

You can also try this package i created, Jiffy.

You can get relative time from now

// This returns time ago from now
Jiffy.now().fromNow(); // a few seconds ago

//You can also pass in a DateTime Object or a string or a list
Jiffy.parseFromDateTime(DateTime.now()).fromNow; // a few seconds ago
//or
Jiffy.parseFromDateTime(DateTime(2018, 10, 25)).fromNow(); // a year ago
Jiffy.parse("2020-10-25").fromNow(); // in a year

Manipulating is also simple in Jiffy

var dateTime = Jiffy.now().add(hours: 3, months: 2);

dateTime.fromNow(); // in 2 months

You can also get relative time from a specified time apart from now

Jiffy.parseFromList([2022, 10, 25])
   .from(Jiffy.parseFromList([2022, 1, 25])); // in 10 months
2019-10-25