2023-11-06 17:46:26 +02:00
|
|
|
extension TimeAgoExtension on DateTime {
|
2024-01-05 07:20:55 +02:00
|
|
|
/// Displays the time difference of this [DateTime] object to the current time as a [String]
|
2023-11-06 17:46:26 +02:00
|
|
|
String timeAgo({bool numericDates = true}) {
|
|
|
|
DateTime date = toLocal();
|
2024-01-05 07:20:55 +02:00
|
|
|
final now = DateTime.now().toLocal();
|
|
|
|
final difference = now.difference(date);
|
2023-11-06 17:46:26 +02:00
|
|
|
|
|
|
|
if (difference.inSeconds < 5) {
|
|
|
|
return 'Just now';
|
|
|
|
} else if (difference.inSeconds < 60) {
|
|
|
|
return '${difference.inSeconds} seconds ago';
|
|
|
|
} else if (difference.inMinutes <= 1) {
|
|
|
|
return (numericDates) ? '1 minute ago' : 'A minute ago';
|
|
|
|
} else if (difference.inMinutes < 60) {
|
|
|
|
return '${difference.inMinutes} minutes ago';
|
|
|
|
} else if (difference.inHours <= 1) {
|
|
|
|
return (numericDates) ? '1 hour ago' : 'An hour ago';
|
|
|
|
} else if (difference.inHours < 60) {
|
|
|
|
return '${difference.inHours} hours ago';
|
|
|
|
} else if (difference.inDays <= 1) {
|
|
|
|
return (numericDates) ? '1 day ago' : 'Yesterday';
|
|
|
|
} else if (difference.inDays < 6) {
|
|
|
|
return '${difference.inDays} days ago';
|
|
|
|
} else if ((difference.inDays / 7).ceil() <= 1) {
|
|
|
|
return (numericDates) ? '1 week ago' : 'Last week';
|
|
|
|
} else if ((difference.inDays / 7).ceil() < 4) {
|
|
|
|
return '${(difference.inDays / 7).ceil()} weeks ago';
|
|
|
|
} else if ((difference.inDays / 30).ceil() <= 1) {
|
|
|
|
return (numericDates) ? '1 month ago' : 'Last month';
|
|
|
|
} else if ((difference.inDays / 30).ceil() < 30) {
|
|
|
|
return '${(difference.inDays / 30).ceil()} months ago';
|
|
|
|
} else if ((difference.inDays / 365).ceil() <= 1) {
|
|
|
|
return (numericDates) ? '1 year ago' : 'Last year';
|
|
|
|
}
|
|
|
|
return '${(difference.inDays / 365).floor()} years ago';
|
|
|
|
}
|
|
|
|
}
|