formatRelative method

String formatRelative()

Returns a relative time string such as: "2 minutes ago", "3 hours ago", "Tomorrow", etc.

Example:

myDate.formatRelative();

Implementation

String formatRelative() {
  if (this == null) return "";

  final now = DateTime.now();
  final dt = this!;

  final diff = now.difference(dt);
  final seconds = diff.inSeconds.abs();
  final minutes = diff.inMinutes.abs();
  final hours = diff.inHours.abs();
  final days = diff.inDays.abs();

  if (isToday()) {
    if (seconds < 60) return "Just now";
    if (minutes < 60) return "$minutes minute(s) ago";
    return "$hours hour(s) ago";
  }

  if (isYesterday()) return "Yesterday";
  if (isTomorrow()) return "Tomorrow";

  if (days < 30) return "$days day(s) ago";
  if (days < 365) return "${(days / 30).floor()} month(s) ago";

  return "${(days / 365).floor()} year(s) ago";
}