Home > OS >  Update the time since upload of an item in flutter app
Update the time since upload of an item in flutter app

Time:03-31

I am working on a news app made with flutter and I am unable to figure out how to calculate the time difference between two times.

For example :- The news was posted ... 10 minutes ago, 5 hours ago, 1 year ago, 10 years ago, etc.

Please help me with this problem by suggesting me a solution.

CodePudding user response:

Have you tried using duration package? https://pub.dev/packages/duration You can check its documentation and see if it matches your needs

CodePudding user response:

answer : 1

Import import 'package:intl/intl.dart'; package and get the time before date and time

import 'package:intl/intl.dart';

class TimeAgo{
  static String timeAgoSinceDate(String dateString, {bool numericDates = true}) {
    DateTime notificationDate = DateFormat("dd-MM-yyyy h:mma").parse(dateString);
    final date2 = DateTime.now();
    final difference = date2.difference(notificationDate);

    if (difference.inDays > 8) {
      return dateString;
    } 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';
    }
  }

} 

And call it this way

TimeAgo.timeAgoSinceDate(item.created_date), // you can pass it in any format date.

answer : 2

with package - https://pub.dev/packages/timeago

To use, import timeago as:

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

To use timeago in widget:

Text(timeago.format(DateTime.fromMillisecondsSinceEpoch(dateTimeMillis))); //or other DateTime object
  • Related