Skip to content

Instantly share code, notes, and snippets.

@AdnaneX
Forked from DineshKachhot/time_ago_since_now.dart
Created August 10, 2020 21:47
Show Gist options
  • Save AdnaneX/2bcf3d4138e2fa9ba59906099361a1cf to your computer and use it in GitHub Desktop.
Save AdnaneX/2bcf3d4138e2fa9ba59906099361a1cf to your computer and use it in GitHub Desktop.
Flutter Time ago calculator
static String timeAgoSinceDate(String dateString, {bool numericDates = true}) {
DateTime date = DateTime.parse(dateString);
final date2 = DateTime.now();
final difference = date2.difference(date);
if ((difference.inDays / 365).floor() >= 2) {
return '${(difference.inDays / 365).floor()} years ago';
} else if ((difference.inDays / 365).floor() >= 1) {
return (numericDates) ? '1 year ago' : 'Last year';
} else if ((difference.inDays / 30).floor() >= 2) {
return '${(difference.inDays / 365).floor()} months ago';
} else if ((difference.inDays / 30).floor() >= 1) {
return (numericDates) ? '1 month ago' : 'Last month';
} else if ((difference.inDays / 7).floor() >= 2) {
return '${(difference.inDays / 7).floor()} weeks ago';
} else if ((difference.inDays / 7).floor() >= 1) {
return (numericDates) ? '1 week ago' : 'Last week';
} else if (difference.inDays >= 2) {
return '${difference.inDays} days ago';
} else if (difference.inDays >= 1) {
return (numericDates) ? '1 day ago' : 'Yesterday';
} else if (difference.inHours >= 2) {
return '${difference.inHours} hours ago';
} else if (difference.inHours >= 1) {
return (numericDates) ? '1 hour ago' : 'An hour ago';
} else if (difference.inMinutes >= 2) {
return '${difference.inMinutes} minutes ago';
} else if (difference.inMinutes >= 1) {
return (numericDates) ? '1 minute ago' : 'A minute ago';
} else if (difference.inSeconds >= 3) {
return '${difference.inSeconds} seconds ago';
} else {
return 'Just now';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment