Humanize Dates with timeago: A Dart Library for Conveying Time Elegantly
Published on by Flutter News Hub
The timeago library is a Dart library that offers an elegant solution for converting dates into human-readable text. Instead of presenting complex date-time formats like "2020-12-12 18:30", timeago allows you to display friendly expressions such as "now", "an hour ago", or "~1y".
Getting Started
Integrating timeago is a breeze with its top-level function, format(date):
import 'package:timeago/timeago.dart' as timeago; main() { final fifteenAgo = DateTime.now().subtract(Duration(minutes: 15)); print(timeago.format(fifteenAgo)); // 15 minutes ago print(timeago.format(fifteenAgo, locale: 'en_short')); // 15m print(timeago.format(fifteenAgo, locale: 'es')); // hace 15 minutos }
Adding Locales
timeago comes with English and Spanish messages loaded by default. To add more languages, use timeago.setLocaleMessages(..). Refer to the locale messages for supported languages here:
https://github.com/andresaraujo/timeago.dart/blob/master/packages/timeago/packages/timeago/lib/src/messages
Overriding Locales and Adding Custom Messages
You can override existing locales or create custom messages by implementing the LookupMessages interface:
// Override "en" locale messages with custom messages timeago.setLocaleMessages('en', MyCustomMessages()); // my_custom_messages.dart class MyCustomMessages implements LookupMessages { @override String prefixAgo() => ''; @override String prefixFromNow() => ''; @override String suffixAgo() => ''; @override String suffixFromNow() => ''; @override String lessThanOneMinute(int seconds) => 'now'; // ... Implement other methods }
Scope
The timeago library focuses on providing:
- A single format function for converting dates into humanized text
- Abstractions for adding and overriding languages
- Community-contributed languages to minimize the need for adding all by default
- Dependency-free operation
timeago_flutter Widgets
The timeago_flutter package offers widgets that integrate with timeago:
- Timeago: A widget that displays a humanized date
- TimerRefresh: A widget that automatically updates its content at a specified interval
- TimerRefreshWidget: A widget that wraps another widget and provides a timer refresh functionality