timeAgo method

String timeAgo({
  1. DateTime? from,
})

Returns a human-readable relative time string.

someDate.timeAgo() // '3 hours ago' / 'just now' / 'in 2 days'

Implementation

String timeAgo({DateTime? from}) {
  final now = from ?? DateTime.now();
  final diff = now.difference(this);
  final future = diff.isNegative;
  final abs = diff.abs();

  String result;
  if (abs.inSeconds < 60) {
    result = 'just now';
  } else if (abs.inMinutes < 60) {
    final m = abs.inMinutes;
    result = '$m ${m == 1 ? 'minute' : 'minutes'}';
  } else if (abs.inHours < 24) {
    final h = abs.inHours;
    result = '$h ${h == 1 ? 'hour' : 'hours'}';
  } else if (abs.inDays < 7) {
    final d = abs.inDays;
    result = '$d ${d == 1 ? 'day' : 'days'}';
  } else if (abs.inDays < 30) {
    final w = abs.inDays ~/ 7;
    result = '$w ${w == 1 ? 'week' : 'weeks'}';
  } else if (abs.inDays < 365) {
    final mo = abs.inDays ~/ 30;
    result = '$mo ${mo == 1 ? 'month' : 'months'}';
  } else {
    final y = abs.inDays ~/ 365;
    result = '$y ${y == 1 ? 'year' : 'years'}';
  }

  if (result == 'just now') return result;
  return future ? 'in $result' : '$result ago';
}