flutterdart

Time ago with specific time format


How do we convert specific time format ("yyyy-MM-dd-HH-mm-ss") to calculate time ago in Flutter? I have the codes below for my android app, however I am trying out Flutter which uses Dart. Can someone provide a pointer here on how we can achieve this?

Date currentDate = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", locale);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String dd = sdf.format(newsDate);
Date gmt = null;
try {
    gmt = sdf.parse(dd);
} catch (ParseException e) {
    e.printStackTrace();
}

long duration = currentDate.getTime() - gmt.getTime();

long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);

Solution

  • This is how I've implemented it:

    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';
    }
    

    then for example, you can embed it inside of an object, and call it like this:

    Text(viewmodel.post.timeAgoSinceDate())