format static method

String format(
  1. DateTime date, {
  2. String? locale,
  3. DateTime? clock,
  4. bool? allowFromNow,
})

Implementation

static String format(DateTime date,
    {String? locale, DateTime? clock, bool? allowFromNow}) {
  final localeVal = locale ?? _default;
  final allowNow = allowFromNow ?? false;
  final messages = _lookupMessagesMap[localeVal] ?? EnMessages();
  final clockTime = clock ?? DateTime.now();
  var elapsed =
      clockTime.millisecondsSinceEpoch - date.millisecondsSinceEpoch;

  String prefix, suffix;

  if (allowNow && elapsed < 0) {
    elapsed = date.isBefore(clockTime) ? elapsed : elapsed.abs();
    prefix = messages.prefixFromNow();
    suffix = messages.suffixFromNow();
  } else {
    prefix = messages.prefixAgo();
    suffix = messages.suffixAgo();
  }

  final num seconds = elapsed / 1000;
  final num minutes = seconds / 60;
  final num hours = minutes / 60;
  final num days = hours / 24;
  final num months = days / 30;
  final num years = days / 365;

  String result;
  if (seconds < 45) {
    result = messages.lessThanOneMinute(seconds.round());
  } else if (seconds < 90) {
    result = messages.aboutAMinute(minutes.round());
  } else if (minutes < 45) {
    result = messages.minutes(minutes.round());
  } else if (minutes < 90) {
    result = messages.aboutAnHour(minutes.round());
  } else if (hours < 24) {
    result = messages.hours(hours.round());
  } else if (hours < 48) {
    result = messages.aDay(hours.round());
  } else if (days < 30) {
    result = messages.days(days.round());
  } else if (days < 60) {
    result = messages.aboutAMonth(days.round());
  } else if (days < 365) {
    result = messages.months(months.round());
  } else if (years < 2) {
    result = messages.aboutAYear(months.round());
  } else {
    result = messages.years(years.round());
  }

  return [prefix, result, suffix]
      .where((str) => str.isNotEmpty)
      .join(messages.wordSeparator());
}