Created
March 1, 2019 06:08
-
-
Save DineshKachhot/bc8cee616f30c323c1dd1e63a4bf65df to your computer and use it in GitHub Desktop.
Flutter Time ago calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; | |
} | |
} |
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 ?
in line number 11, you might want to divide difference of days with 30 , instead of 365, in case of months.
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?
Just reverse the if/else statements starting with ''JustNow''
here's mine, with reversed if statements :
https://gist.github.com/jinnosux/e04f58e216fb9406d53bca522f98e3da
Thanks, Dinesh.
dateString example ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was helpful. I have reversed the order of the if/else statements such that it runs faster for recent dates