How to get Time Ago from DateTime in Flutter/Dart

In this example, you will learn how to get full-length time ago from date and time in Dart or Flutter. I checked many packages but all give a short time ago string from DateTime. Here, we have written a function that returns the full length of time ago with Dart and Flutter. 

String time_passed(DateTime datetime, {bool full = true}) {
    DateTime now = DateTime.now();
    DateTime ago = datetime;
    Duration dur = now.difference(ago);
    int days = dur.inDays;
    int years = (days / 365).toInt();
    int months =  ((days - (years * 365)) / 30).toInt();
    int weeks = ((days - (years * 365 + months * 30)) / 7).toInt();
    int rdays = days - (years * 365 + months * 30 + weeks * 7).toInt();
    int hours = (dur.inHours % 24).toInt();
    int minutes = (dur.inMinutes % 60).toInt();
    int seconds = (dur.inSeconds % 60).toInt();
    var diff = {
          "d":rdays,
          "w":weeks,
          "m":months,
          "y":years,
          "s":seconds,
          "i":minutes,
          "h":hours
    };

    Map str = {
        'y':'year',
        'm':'month',
        'w':'week',
        'd':'day',
        'h':'hour',
        'i':'minute',
        's':'second',
    };

    str.forEach((k, v){
        if (diff[k]! > 0) {
            str[k] = diff[k].toString()  +  ' ' + v.toString() +  (diff[k]! > 1 ? 's' : '');
        } else {
            str[k] = "";
        }
    });
    str.removeWhere((index, ele)=>ele == "");
    List<String> tlist = [];
    str.forEach((k, v){
      tlist.add(v);
    });
    if(full){
      return str.length > 0?tlist.join(", ") + " ago":"Just Now";
    }else{
      return str.length > 0?tlist[0] + " ago":"Just Now";
    }
}

This function returns the full length of time ago, and "Just Now" too. If you want a small version, pass false to the full parameter of this function. 

print(DateTime.now()); //2023-01-09 12:17:37.830145

String timeago = time_passed(DateTime.parse("2021-01-04 11:47:00"));
print(timeago); //2 years, 5 days, 30 minutes, 37 seconds ago

String timeago1 = time_passed(DateTime.parse("2021-01-04 11:47:00"), full: false);
print(timeago1); //2 years ago

String timeago2 = time_passed(DateTime.parse("2023-01-04 11:47:00"), full: false);
print(timeago2); //5 days ago

String timeago3 = time_passed(DateTime.now(), full: false);
print(timeago3); //Just Now

Here, there is a different kind of usability of this function to generate "time ago" or "just now" from a DateTime in Dart or Flutter.

In this way, you can generate a "time ago" string from DateTime in Dart or Flutter. 

No any Comments on this Article


Please Wait...