Code

void main() {
  DateTime now = DateTime.now();

  // Different date-time examples
  DateTime fiveYearsAgo = now.subtract(Duration(days: 5 * 365));
  DateTime sixMonthsAgo = now.subtract(Duration(days: 6 * 30));
  DateTime fiveWeeksAgo = now.subtract(Duration(days: 5 * 7));
  DateTime sixDaysAgo = now.subtract(Duration(days: 6));
  DateTime fiveHoursAgo = now.subtract(Duration(hours: 5));
  DateTime sixMinutesAgo = now.subtract(Duration(minutes: 6));
  DateTime justNow = now.subtract(Duration(seconds: 30));

  print("5 years ago: ${convertToAgo(fiveYearsAgo)}");
  print("6 months ago: ${convertToAgo(sixMonthsAgo)}");
  print("5 weeks ago: ${convertToAgo(fiveWeeksAgo)}");
  print("6 days ago: ${convertToAgo(sixDaysAgo)}");
  print("5 hours ago: ${convertToAgo(fiveHoursAgo)}");
  print("6 minutes ago: ${convertToAgo(sixMinutesAgo)}");
  print("Just now: ${convertToAgo(justNow)}");
}

String convertToAgo(DateTime? input) {
  if (input == null) {
    return 'Invalid date';
  }

  Duration diff = DateTime.now().difference(input);
  final numDays = diff.inDays;

  if (numDays >= 365) {
    final numYears = (numDays / 365).floor();
    return numYears == 1 ? '1 year ago' : '$numYears year ago';
  } else if (numDays >= 30) {
    final numMonths = (numDays / 30).floor();
    return numMonths == 1 ? '1 month ago' : '$numMonths month ago';
  } else if (numDays >= 7) {
    final numWeeks = (numDays / 7).floor();
    return numWeeks == 1 ? '1 week ago' : '$numWeeks week ago';
  } else if (numDays >= 1) {
    return numDays == 1 ? '1 dy ago' : '$numDays day ago';
  } else if (diff.inHours >= 1) {
    final numHours = diff.inHours;
    return numHours == 1 ? '1 hours ago' : '$numHours hours ago';
  } else if (diff.inMinutes >= 1) {
    final numMinutes = diff.inMinutes;
    return numMinutes == 1 ? '1 min ago' : '$numMinutes min ago';
  } else {
    return 'just now';
  }
}

 

Output

Support On Demand!

Flutter