'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



Solution 1:[1]

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

Solution 2:[2]

You can also try this package, Jiffy.

You can get relative time from now

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

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

Manipulating is also simple in Jiffy

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

dateTime.fromNow(); // in 2 months

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

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

Solution 3:[3]

I simplify Paresh's answer by using DateTime extension

create a new dart file called date_time_extension.dart and then write code like this

extension DateTimeExtension on DateTime {


  String timeAgo({bool numericDates = true}) {
    final date2 = DateTime.now();
    final difference = date2.difference(this);

    if ((difference.inDays / 7).floor() >= 1) {
      return (numericDates) ? '1 week ago' : 'Last week';
    } else if (difference.inDays >= 2) {
      return '${difference.inDays} days ago';
    } else if (difference.inDays >= 1) {
      return (numericDates) ? '1 day ago' : 'Yesterday';
    } else if (difference.inHours >= 2) {
      return '${difference.inHours} hours ago';
    } else if (difference.inHours >= 1) {
      return (numericDates) ? '1 hour ago' : 'An hour ago';
    } else if (difference.inMinutes >= 2) {
      return '${difference.inMinutes} minutes ago';
    } else if (difference.inMinutes >= 1) {
      return (numericDates) ? '1 minute ago' : 'A minute ago';
    } else if (difference.inSeconds >= 3) {
      return '${difference.inSeconds} seconds ago';
    } else {
      return 'Just now';
    }
  }

  
}

and then, use it like this

import 'package:utilities/extensions/date_time_extension.dart'; // <--- import the file you just create

product.createdAt.timeAgo(numericDates: false) // use it on your DateTime property

Solution 4:[4]

A variation on @Alex289's answer

extension DateHelpers on DateTime {

  String toTimeAgoLabel({bool isIntervalNumericVisible = true}) {
    final now = DateTime.now();
    final durationSinceNow = now.difference(this);

    final inDays = durationSinceNow.inDays;
    if (inDays >= 1) {
      return (inDays / 7).floor() >= 1
          ? isIntervalNumericVisible ? '1 week ago' : 'Last week'
          : inDays >= 2
              ? '$inDays days ago'
              : isIntervalNumericVisible
                  ? '1 day ago'
                  : 'Yesterday';
    }

    final inHours = durationSinceNow.inHours;
    if (inHours >= 1) {
      return inHours >= 2
          ? '$inHours hours ago'
          : isIntervalNumericVisible
              ? '1 hour ago'
              : 'An hour ago';
    }

    final inMinutes = durationSinceNow.inMinutes;
    if (inMinutes >= 2) {
      return inHours >= 2
          ? '$inMinutes minutes ago'
          : isIntervalNumericVisible
              ? '1 minute ago'
              : 'A minute ago';
    }

    final inSeconds = durationSinceNow.inSeconds;
    return inSeconds >= 3 ? '$inSeconds seconds ago' : 'Just now';
  }
}

Solution 5:[5]

You can use this Method which will give you times ago.

String convertToAgo(String dateTime) {
  DateTime input =
      DateFormat('yyyy-MM-DDTHH:mm:ss.SSSSSSZ').parse(dateTime, true);
  Duration diff = DateTime.now().difference(input);

  if (diff.inDays >= 1) {
    return '${diff.inDays} day${diff.inDays == 1 ? '' : 's'} ago';
  } else if (diff.inHours >= 1) {
    return '${diff.inHours} hour${diff.inHours == 1 ? '' : 's'} ago';
  } else if (diff.inMinutes >= 1) {
    return '${diff.inMinutes} minute${diff.inMinutes == 1 ? '' : 's'} ago';
  } else if (diff.inSeconds >= 1) {
    return '${diff.inSeconds} second${diff.inSeconds == 1 ? '' : 's'} ago';
  } else {
    return 'just now';
  }
}

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 Mohsin Naeem
Solution 2
Solution 3
Solution 4
Solution 5 Shailandra Rajput