Skip to content

Instantly share code, notes, and snippets.

@jinnosux
Created November 7, 2020 15:32
Show Gist options
  • Save jinnosux/e04f58e216fb9406d53bca522f98e3da to your computer and use it in GitHub Desktop.
Save jinnosux/e04f58e216fb9406d53bca522f98e3da to your computer and use it in GitHub Desktop.
Flutter time ago implementation
String timeAgoSinceDate({bool numericDates = true}) {
DateTime date = this.createdTime.toLocal();
final date2 = DateTime.now().toLocal();
final difference = date2.difference(date);
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';
}
@ramsmart-inno
Copy link

how to pass Date with Time?

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