getRelativeTime function
Get a relative time string for a single item matching CometChatDate.setDayTime:
- Today (< 24h): Time only (e.g., "2:35 PM")
- Yesterday (24–48h): "Yesterday"
- This week (2–7 days): Day name (e.g., "Monday")
- Older (> 7 days): Full date (e.g., "25/05/2026")
Implementation
String getRelativeTime(int sentAtSeconds, String locale) {
final now = DateTime.now();
final sentAt = DateTime.fromMillisecondsSinceEpoch(sentAtSeconds * 1000);
final today = DateTime(now.year, now.month, now.day);
final yesterday = today.subtract(const Duration(days: 1));
final sentAtDay = DateTime(sentAt.year, sentAt.month, sentAt.day);
if (sentAtDay == today) {
// Today — show time only (e.g., "2:35 PM")
return DateFormat.jm(locale).format(sentAt);
} else if (sentAtDay == yesterday) {
// Yesterday
return 'Yesterday';
} else if (now.difference(sentAt).inDays < 7) {
// Within this week — show day name (e.g., "Monday")
return DateFormat.EEEE(locale).format(sentAt);
} else {
// Older — show full date (e.g., "25/05/2026")
return DateFormat('dd/MM/yyyy').format(sentAt);
}
}