How to display time ago like Youtube in Flutter
Asked Answered
Z

3

5

I'm writing a flutter app to clone some Youtube functionalities using Youtube API V3.

The app fetches video timestamp as a String from youtube video API

Each timestamp has this format :

YYYY-MM-DDTHH:MM:SSZ

One example would be:

2020-07-12T20:42:19Z

I would like to display in a text :

  • 1 hour
  • 1 hours ago
  • 4 weeks ago
  • 11 months ago
  • 1 year ago
  • ...
Zingale answered 13/7, 2020 at 10:27 Comment(0)
Z
13

I've created an extension on String

 extension StringExtension on String {
  static String displayTimeAgoFromTimestamp(String timestamp) {
    final year = int.parse(timestamp.substring(0, 4));
    final month = int.parse(timestamp.substring(5, 7));
    final day = int.parse(timestamp.substring(8, 10));
    final hour = int.parse(timestamp.substring(11, 13));
    final minute = int.parse(timestamp.substring(14, 16));

    final DateTime videoDate = DateTime(year, month, day, hour, minute);
    final int diffInHours = DateTime.now().difference(videoDate).inHours;

    String timeAgo = '';
    String timeUnit = '';
    int timeValue = 0;

    if (diffInHours < 1) {
      final diffInMinutes = DateTime.now().difference(videoDate).inMinutes;
      timeValue = diffInMinutes;
      timeUnit = 'minute';
    } else if (diffInHours < 24) {
      timeValue = diffInHours;
      timeUnit = 'hour';
    } else if (diffInHours >= 24 && diffInHours < 24 * 7) {
      timeValue = (diffInHours / 24).floor();
      timeUnit = 'day';
    } else if (diffInHours >= 24 * 7 && diffInHours < 24 * 30) {
      timeValue = (diffInHours / (24 * 7)).floor();
      timeUnit = 'week';
    } else if (diffInHours >= 24 * 30 && diffInHours < 24 * 12 * 30) {
      timeValue = (diffInHours / (24 * 30)).floor();
      timeUnit = 'month';
    } else {
      timeValue = (diffInHours / (24 * 365)).floor();
      timeUnit = 'year';
    }

    timeAgo = timeValue.toString() + ' ' + timeUnit;
    timeAgo += timeValue > 1 ? 's' : '';

    return timeAgo + ' ago';
  }
}

Then call in text:

StringExtension.displayTimeAgoFromTimestamp(video.timestamp)
Zingale answered 13/7, 2020 at 10:40 Comment(0)
T
3

You can use the timeago package

example code below

import 'package:timeago/timeago.dart' as timeago;

main() {
    final fifteenAgo = new DateTime.now().subtract(new Duration(minutes: 15));

    print(timeago.format(fifteenAgo)); // 15 minutes ago
    print(timeago.format(fifteenAgo, locale: 'en_short')); // 15m
    print(timeago.format(fifteenAgo, locale: 'es')); // hace 15 minutos
}

to use it with the YYYY-MM-DDTHH:MM:SSZ time format you can convert the String to a DateTime then perform the operation on the DateTime variable

DateTime time = DateTime.parse("2020-07-12T20:42:19Z");
print(timeago.format(time));
Tyrothricin answered 13/7, 2020 at 10:30 Comment(1)
Thanks but I already tried it and the problem is that instead of printing "45 minutes ago" it prints "about an hour ago". This package is really good but in my case there's some messages I do not wantZingale
F
0

I've created reusable function for sample, this might be helpful!!

import 'package:intl/intl.dart';
//for DateTime manipulation need to add this package
import 'package:timeago/timeago.dart' as timeago;
void main(){
//creating this getTimeAgo function to format dateTime with user inputs
    dynamic getTimeAgo(DateTime d) {
      dynamic value = "";
//setting current time variable now
      final now = DateTime.now();
//converting the user provided date to LocalTime
      final recvDate = d.toLocal();
//declaring today's date in today variable
      final today = DateTime(now.year, now.month, now.day);
//declaring yesterday's date in yesterday variable
      final yesterday = DateTime(now.year, now.month, now.day - 1);
//declaring user provided date's in date variable 
      final date = DateTime(recvDate.year, recvDate.month, recvDate.day);
//comparing today's date is equal to user provided date then return value with timeAgo flutter package response
      if (date == today) {
        final curtimeNow = timeago.format(d);
              if (curtimeNow == 'a day ago') {
                   value = "1 day ago";
              } else if (curtimeNow == 'about an hour ago') {
                   value = "1 hour ago";
              } else {
                   value = curtimeNow;
              }
      } //comparing yesterday's date is equal to user provided date then return 1 day ago 
      else if (date == yesterday) {
                 value='1 day ago';
      } //else the user provided date then return as the date format of dd MMM yyyy Eg. 10 Mar 2022
      else {
        value = DateFormat('dd MMM yyyy').format(date);
      }
     //returning the response
      return value;
    }
    
    //declaring the date which is to used be formatted
    var recvdDateTime=DateTime.now().subtract(Duration(minutes: 45));;
    //calling the getTimeAgo (fn) with user input
    getTimeAgo(DateTime.parse(recvdDateTime));
}
Faraway answered 13/12, 2022 at 5:55 Comment(2)
it's important to provide not only code, but also a clear and concise explanation of what the code is doing and why it is relevant to the question or problem at hand. This helps other users understand the context and purpose of the code, and can also make it easier for them to understand how to modify or extend the code to fit their own needs.Sate
thank you sir @DSDmark, now i have added the comment for code implementation. please suggest if anything needed.Faraway

© 2022 - 2025 — McMap. All rights reserved.