timeAgo function

String timeAgo(
  1. DateTime date,
  2. String tr(
    1. String
    ),
  3. String locale
)

Returns a string representing the time ago from the given date. Requires a translation function tr to translate the string into the given locale.

Implementation

String timeAgo(DateTime date, String Function(String) tr, String locale) {
  final delta = DateTime.now().difference(date);
  final a = DurationFormattedEnglish(delta.inMicroseconds);
  const K = 'time_ago';
  if (delta.inDays == 1) {
    return tr('$K.yesterday');
  }
  if (delta.inDays > 3) {
    return dayAgo(date, tr, locale);
  }
  if (delta.inDays > 1) {
    return '${a.d}${tr('$K.d')}';
  }
  if (delta.inHours > 1) {
    return '${a.h}${tr('$K.h')}';
  }
  if (delta.inMinutes > 1) {
    return '${a.m}${tr('$K.m')}';
  }
  if (delta.inSeconds > 30) {
    return '${a.s}${tr('$K.s')}';
  }
  return tr('$K.now');
}