Converting DateTime to time ago in Dart/Flutter
Asked Answered
U

9

46

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

Uncial answered 8/11, 2018 at 7:51 Comment(1)
its good solutionRriocard
A
51

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

Azaleeazan answered 16/1, 2019 at 8:11 Comment(0)
P
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
Poyssick answered 25/10, 2019 at 7:5 Comment(1)
I find this simpler than timeago, thank you!Larvicide
Z
12

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
Zaffer answered 8/3, 2022 at 3:15 Comment(1)
This does not work for datetime more than one week.Colpitis
P
1

If you just want to use Datetime library this is the way you can do it.

void main() {
  final currentTime = DateTime.now();
  print('Current time: $currentTime');
  final threeWeeksAgo = currentTime.subtract(const Duration(days: 21));
  print('Three weeks ago: $threeWeeksAgo');
}

This is what you get:

Current time: 2022-09-29 11:26:58.350
Three weeks ago: 2022-09-08 11:26:58.350
Pr answered 29/9, 2022 at 17:28 Comment(0)
T
1
String timeAgoCustom(DateTime d) {             // <-- Custom method Time Show  (Display Example  ==> 'Today 7:00 PM')     // WhatsApp Time Show Status Shimila
 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 "${DateFormat.E().add_jm().format(d)}";
 if (diff.inHours > 0)
  return "Today ${DateFormat('jm').format(d)}";
 if (diff.inMinutes > 0)
  return "${diff.inMinutes} ${diff.inMinutes == 1 ? "minute" : "minutes"} ago";
 return "just now";
}

Add This Package --> intl: ^0.17.0



Time Show Example (Today 8:29 PM)
Thickskinned answered 14/11, 2022 at 15:9 Comment(0)
C
0

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';
  }
}
Cloyd answered 5/5, 2022 at 6:8 Comment(0)
R
0

Hope you got the answer! you just need to past your timestamp value in this method and you get a time ago formatted string.

String getVerboseDateTimeRepresentation(DateTime dateTime) {
    DateTime now = DateTime.now().toLocal();

    DateTime localDateTime = dateTime.toLocal();

    if (localDateTime.difference(now).inDays == 0) {
      var differenceInHours = localDateTime.difference(now).inHours.abs();
      var differenceInMins = localDateTime.difference(now).inMinutes.abs();

      if (differenceInHours > 0) {
        return '$differenceInHours hours ago';
      } else if (differenceInMins > 2) {
        return '$differenceInMins mins ago';
      } else {
        return 'Just now';
      }
    }

    String roughTimeString = DateFormat('jm').format(dateTime);

    if (localDateTime.day == now.day &&
        localDateTime.month == now.month &&
        localDateTime.year == now.year) {
      return roughTimeString;
    }

    DateTime yesterday = now.subtract(const Duration(days: 1));

    if (localDateTime.day == yesterday.day &&
        localDateTime.month == now.month &&
        localDateTime.year == now.year) {
      return 'Yesterday';
    }

    if (now.difference(localDateTime).inDays < 4) {
      String weekday = DateFormat(
        'EEEE',
      ).format(localDateTime);

      return '$weekday, $roughTimeString';
    }

    return '${DateFormat('yMd').format(dateTime)}, $roughTimeString';
  }
Roma answered 21/7, 2022 at 5:20 Comment(0)
M
0
Text(
Jiffy.parse(jiffyDateTime.toString()).fromNow(),
style: TextStyle(color: BrandColors.grey, fontSize: 12)
)

No need to parse date&time format even in the list, make sure your pattern will follow this 'yyyy-MM-dd'

Miry answered 12/2, 2024 at 5:59 Comment(0)
D
-1

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 inMinutes >= 2
          ? '$inMinutes minutes ago'
          : isIntervalNumericVisible
              ? '1 minute ago'
              : 'A minute ago';
    }

    final inSeconds = durationSinceNow.inSeconds;
    return inSeconds >= 3 ? '$inSeconds seconds ago' : 'Just now';
  }
}
Discombobulate answered 13/4, 2022 at 1:25 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.