relative static method

String relative(
  1. DateTime d, {
  2. required DateTime now,
})

The human answer to "when": "Today", "Yesterday", "Tomorrow", "3 days ago", "In 2 days", and past a week the plain dayMonth.

Measured in CALENDAR days, not elapsed hours: 11pm to 1am is one sleep and the reader calls it yesterday, however few hours it was. It gives up at a week because "In 23 days" is a worse answer than the date.

Implementation

static String relative(DateTime d, {required DateTime now}) {
  // Calendar days compared as UTC dates: two LOCAL midnights across a
  // daylight-saving change are 23 or 25 hours apart, and `inDays` would
  // floor the short one to zero — tomorrow would read "Today", and the
  // answer would hang on the machine's time zone.
  final days = DateTime.utc(
    d.year,
    d.month,
    d.day,
  ).difference(DateTime.utc(now.year, now.month, now.day)).inDays;
  if (days == 0) return 'Today';
  if (days == -1) return 'Yesterday';
  if (days == 1) return 'Tomorrow';
  if (days < -1 && days > -7) return '${-days} days ago';
  if (days > 1 && days < 7) return 'In $days days';
  return dayMonth(d);
}