Skip to content

Instantly share code, notes, and snippets.

@DineshKachhot
Created March 1, 2019 06:08
Show Gist options
  • Save DineshKachhot/bc8cee616f30c323c1dd1e63a4bf65df to your computer and use it in GitHub Desktop.
Save DineshKachhot/bc8cee616f30c323c1dd1e63a4bf65df 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';
}
}
@frroliveira
Copy link

This was helpful. I have reversed the order of the if/else statements such that it runs faster for recent dates

@nimi0112
Copy link

This was helpful. I have reversed the order of the if/else statements such that it runs faster for recent dates

@frroliveira can you also post your code in comments please ?

@mahi2swt
Copy link

in line number 11, you might want to divide difference of days with 30 , instead of 365, in case of months.

@Sopheak0
Copy link

This was helpful. I have reversed the order of the if/else statements such that it runs faster for recent dates

can you post your code, pls?

@Phanuel121
Copy link

Just reverse the if/else statements starting with ''JustNow''

@jinnosux
Copy link

jinnosux commented Nov 7, 2020

here's mine, with reversed if statements :
https://gist.github.com/jinnosux/e04f58e216fb9406d53bca522f98e3da

Thanks, Dinesh.

@theappideasankit
Copy link

dateString example ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment