toRelativeString method

String toRelativeString()

Approximate relative: in 2 hours, 3 minutes ago, just now

Implementation

String toRelativeString() {
  final abs = this.abs();

  if (abs.inSeconds < 10) return 'just now';

  final String body;
  if (abs.inDays >= 365) {
    final y = (abs.inDays / 365).round();
    body = '$y ${y == 1 ? 'year' : 'years'}';
  } else if (abs.inDays >= 30) {
    final mo = (abs.inDays / 30).round();
    body = '$mo ${mo == 1 ? 'month' : 'months'}';
  } else if (abs.inDays >= 1) {
    body = '${abs.inDays} ${abs.inDays == 1 ? 'day' : 'days'}';
  } else if (abs.inHours >= 1) {
    body = '${abs.inHours} ${abs.inHours == 1 ? 'hour' : 'hours'}';
  } else if (abs.inMinutes >= 1) {
    body = '${abs.inMinutes} ${abs.inMinutes == 1 ? 'minute' : 'minutes'}';
  } else {
    body = '${abs.inSeconds} seconds';
  }

  return isNegative ? '$body ago' : 'in $body';
}