35.2 C
New York
Tuesday, August 9, 2022

2 ways to convert DateTime to time ago in Flutter

- Advertisement -

This article shows you 2 approaches to convert DateTime to time ago format in Flutter (and Dart too), for example, 5 minutes ago, 1 day ago, 2 days ago… The first one is using the difference() method provided by the DateTime class, and the second one is using a third-party plugin.

Using the difference() method

This solution is for people who want to use as few third-party plugins as possible in their projects. Advertisements

Define a self-made converting function:

String convertToAgo(DateTime input){
  Duration diff = DateTime.now().difference(input);
  
  if(diff.inDays >= 1){
    return '${diff.inDays} day(s) ago';
  } else if(diff.inHours >= 1){
    return '${diff.inHours} hour(s) ago';
  } else if(diff.inMinutes >= 1){
    return '${diff.inMinutes} minute(s) ago';
  } else if (diff.inSeconds >= 1){
    return '${diff.inSeconds} second(s) ago';
  } else {
    return 'just now';
  }
}

Try it:

void main() {
  DateTime time1 = DateTime.parse("2022-01-20 20:18:04Z");
  print(convertToAgo(time1));

  DateTime time2 = DateTime.utc(2022, 02, 9);
  print(convertToAgo(time2));
}

The output depends on WHEN you run the code. Here is mine on February 12, 2022:

22 day(s) ago
3 day(s) ago

AdvertisementsNote: You can improve the converting function by checking between singular and plural nouns (day/days, hour/hours, minute/minutes, second/seconds) to remove the parentheses. For example:

if(diff.inDays > 1){
    return '${diff.inDays} days ago';
} else if(diff.inDays == 1){
    return 'a day ago';
}

Using a third-party plugin

This solution is for people who want to write as little code as possible.

The plugin we’ll use is called timeago.

1. Add timeago and its version to the dependencies section in your pubspec.yaml file by performing the following:

dart pub add timeago
Advertisements

2. Run the following command:

flutter pub get

3. Import it to your code:

import 'package:timeago/timeago.dart' as timeago;

4. Use it in the code:

import 'package:timeago/timeago.dart' as timeago;

main() {
  final DateTime time1 = DateTime.parse("1987-07-20 20:18:04Z");
  final DateTime time2 = DateTime.utc(1989, 11, 9);

  print(timeago.format(time1));
  print(timeago.format(time2, locale: 'en_short'));
}

Output:

35 years ago
32 yr

Conclusion

We’ve walked through more than one technique to turn DateTime into the time ago format in Dart and Flutter. Choose the approach that suits your need. If you’d like to learn more about date-time stuff, take a look at the following articles:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

- Advertisement -

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles