toTimeagoFormat method
String
toTimeagoFormat({
- bool showTimeForOveraged = true,
- TimestampLocale locale = const TimestampLocale(),
- String timePattern = 'hh:mm a',
- DateTime? referenceTime,
- Duration timeagoLimit = const Duration(hours: 1),
Returns a human-friendly notification timestamp string relative to now.
Parameters:
showTimeForOveraged— whether to append the time of day. Defaults totrue.locale— override labels (for i18n / custom wording).timePattern—intlDateFormatpattern for the time portion. Defaults to'hh:mm a'(12-hour with AM/PM).referenceTime— the "now" used for comparison. Useful for testing or showing relative times against a non-current anchor.timeagoLimit— the maximum age for which the timeago format ("Xm ago") is used. Defaults to 1 hour. After this limit, it falls back to 'Today', 'Yesterday', etc.
Implementation
String toTimeagoFormat({
bool showTimeForOveraged = true,
TimestampLocale locale = const TimestampLocale(),
String timePattern = 'hh:mm a',
DateTime? referenceTime,
Duration timeagoLimit = const Duration(hours: 1),
}) {
if (this == null) return locale.unknownTime;
final dateTime = this!;
final now = referenceTime ?? DateTime.now();
final difference = now.difference(dateTime);
final timeFormat = DateFormat(timePattern).format(dateTime);
// ── < 1 minute ──────────────────────────────────────────────────────────
if (difference.inMinutes < 1) {
return locale.justNow;
}
// ── Less than timeagoLimit (default: 1 hour) ────────────────────────────
if (difference.compareTo(timeagoLimit) < 0) {
if (difference.inHours < 1) {
return locale.minutesAgo(difference.inMinutes);
} else {
return locale.hoursAgo(difference.inHours);
}
}
// ── Today ────────────────────────────────────────────────────────────────
if (DateUtils.isSameDay(dateTime, now)) {
return timeFormat; // e.g. "02:30 PM"
}
// ── Yesterday ────────────────────────────────────────────────────────────
final yesterday = now.subtract(const Duration(days: 1));
if (DateUtils.isSameDay(dateTime, yesterday)) {
return showTimeForOveraged
? '${locale.yesterday}, $timeFormat'
: locale.yesterday;
}
// ── Within the past 7 days (same week feel) ──────────────────────────────
if (difference.inDays < 7) {
final weekday = DateFormat('EEEE').format(dateTime); // "Monday"
return showTimeForOveraged ? '$weekday, $timeFormat' : weekday;
}
// ── Same calendar year ───────────────────────────────────────────────────
if (dateTime.year == now.year) {
final date = DateFormat('d MMM').format(dateTime); // "15 Jan"
return showTimeForOveraged ? '$date, $timeFormat' : date;
}
// ── Different year ───────────────────────────────────────────────────────
final date = DateFormat('d MMM yyyy').format(dateTime); // "15 Jan 2024"
return showTimeForOveraged ? '$date, $timeFormat' : date;
}