在Dart/Flutter中将DateTime转换为时间之前

hgc7kmma  于 2022-11-17  发布在  Flutter
关注(0)|答案(9)|浏览(168)

问题是如何将Dart DateTime格式化为一个字符串,该字符串表示经过的时间,类似于您在Stack Overflow上看到的时间显示方式。
还有比这更好的方法吗

String timeAgo(DateTime d) {
 Duration diff = DateTime.now().difference(d);
 if (diff.inDays > 365)
  return "${(diff.inDays / 365).floor()} ${(diff.inDays / 365).floor() == 1 ? "year" : "years"} ago";
 if (diff.inDays > 30)
  return "${(diff.inDays / 30).floor()} ${(diff.inDays / 30).floor() == 1 ? "month" : "months"} ago";
 if (diff.inDays > 7)
  return "${(diff.inDays / 7).floor()} ${(diff.inDays / 7).floor() == 1 ? "week" : "weeks"} ago";
 if (diff.inDays > 0)
  return "${diff.inDays} ${diff.inDays == 1 ? "day" : "days"} ago";
 if (diff.inHours > 0)
  return "${diff.inHours} ${diff.inHours == 1 ? "hour" : "hours"} ago";
 if (diff.inMinutes > 0)
  return "${diff.inMinutes} ${diff.inMinutes == 1 ? "minute" : "minutes"} ago";
 return "just now";
}

谢谢你,希望它能帮助其他人

o4hqfura

o4hqfura1#

我使用timeago的确切目的,并发现它相当有用。它有多种格式和不同的语言支持以及。

scyqe7ek

scyqe7ek2#

你也可以试试这个软件包Jiffy
您可以获得从现在开始的相对时间

// This returns time ago from now
Jiffy().fromNow(); // a few seconds ago

//You can also pass in a DateTime Object or a string or a list
Jiffy(DateTime.now()).fromNow; // a few seconds ago
//or
Jiffy(DateTime(2018, 10, 25)).fromNow(); // a year ago
Jiffy("2020-10-25").fromNow(); // in a year

在Jiffy中操作也很简单

var dateTime = Jiffy().add(hours: 3, months: 2);

dateTime.fromNow(); // in 2 months

您还可以从指定的时间获取相对时间,而不是现在

Jiffy([2022, 10, 25]).from([2022, 1, 25]); // in 10 months
afdcj2ne

afdcj2ne3#

我通过使用DateTime扩展简化了Paresh's answer
创建一个名为date_time_extension.dart的新dart文件,然后编写如下代码

extension DateTimeExtension on DateTime {

  String timeAgo({bool numericDates = true}) {
    final date2 = DateTime.now();
    final difference = date2.difference(this);

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

  
}

然后像这样使用它

import 'package:utilities/extensions/date_time_extension.dart'; // <--- import the file you just create

product.createdAt.timeAgo(numericDates: false) // use it on your DateTime property
eni9jsuy

eni9jsuy4#

我使用timeago的确切目的,并发现它相当有用。
此解决方案适用于希望编写尽可能少的代码的人。
1.通过执行以下操作,将timeago及其版本添加到pubspec.yaml文件得dependencies部分:
dart pub add timeago
1.运行以下命令:
flutter pub get
1.将其导入到代码中:
import 'package:timeago/timeago.dart' as timeago;
1.在代码中使用它:

main() {
   final DateTime time1 = DateTime.parse("2022-04-20 20:18:04Z");
   final DateTime time2 = DateTime.utc(2020, 6, 2);
   print(timeago.format(time1));
   print(timeago.format(time2, locale: 'en_short'));
 }

输出:2 months ago2 yr

irlmq6kh

irlmq6kh5#

你可以使用这个方法,这将给予你以前的时间。

String convertToAgo(String dateTime) {
  DateTime input =
      DateFormat('yyyy-MM-DDTHH:mm:ss.SSSSSSZ').parse(dateTime, true);
  Duration diff = DateTime.now().difference(input);

  if (diff.inDays >= 1) {
    return '${diff.inDays} day${diff.inDays == 1 ? '' : 's'} ago';
  } else if (diff.inHours >= 1) {
    return '${diff.inHours} hour${diff.inHours == 1 ? '' : 's'} ago';
  } else if (diff.inMinutes >= 1) {
    return '${diff.inMinutes} minute${diff.inMinutes == 1 ? '' : 's'} ago';
  } else if (diff.inSeconds >= 1) {
    return '${diff.inSeconds} second${diff.inSeconds == 1 ? '' : 's'} ago';
  } else {
    return 'just now';
  }
}
qybjjes1

qybjjes16#

希望你得到了答案!你只需要在这个方法中传递你的时间戳值,你就会得到一个时间以前的格式化字符串。

String getVerboseDateTimeRepresentation(DateTime dateTime) {
    DateTime now = DateTime.now().toLocal();

    DateTime localDateTime = dateTime.toLocal();

    if (localDateTime.difference(now).inDays == 0) {
      var differenceInHours = localDateTime.difference(now).inHours.abs();
      var differenceInMins = localDateTime.difference(now).inMinutes.abs();

      if (differenceInHours > 0) {
        return '$differenceInHours hours ago';
      } else if (differenceInMins > 2) {
        return '$differenceInMins mins ago';
      } else {
        return 'Just now';
      }
    }

    String roughTimeString = DateFormat('jm').format(dateTime);

    if (localDateTime.day == now.day &&
        localDateTime.month == now.month &&
        localDateTime.year == now.year) {
      return roughTimeString;
    }

    DateTime yesterday = now.subtract(const Duration(days: 1));

    if (localDateTime.day == yesterday.day &&
        localDateTime.month == now.month &&
        localDateTime.year == now.year) {
      return 'Yesterday';
    }

    if (now.difference(localDateTime).inDays < 4) {
      String weekday = DateFormat(
        'EEEE',
      ).format(localDateTime);

      return '$weekday, $roughTimeString';
    }

    return '${DateFormat('yMd').format(dateTime)}, $roughTimeString';
  }
mqxuamgl

mqxuamgl7#

如果你只是想使用Datetime库,这是你可以做到的。

void main() {
  final currentTime = DateTime.now();
  print('Current time: $currentTime');
  final threeWeeksAgo = currentTime.subtract(const Duration(days: 21));
  print('Three weeks ago: $threeWeeksAgo');
}

这是你得到的:

Current time: 2022-09-29 11:26:58.350
Three weeks ago: 2022-09-08 11:26:58.350
scyqe7ek

scyqe7ek8#

String timeAgoCustom(DateTime d) {             // <-- Custom method Time Show  (Display Example  ==> 'Today 7:00 PM')     // WhatsApp Time Show Status Shimila
 Duration diff = DateTime.now().difference(d);
 if (diff.inDays > 365)
  return "${(diff.inDays / 365).floor()} ${(diff.inDays / 365).floor() == 1 ? "year" : "years"} ago";
 if (diff.inDays > 30)
  return "${(diff.inDays / 30).floor()} ${(diff.inDays / 30).floor() == 1 ? "month" : "months"} ago";
 if (diff.inDays > 7)
  return "${(diff.inDays / 7).floor()} ${(diff.inDays / 7).floor() == 1 ? "week" : "weeks"} ago";
 if (diff.inDays > 0)
  return "${DateFormat.E().add_jm().format(d)}";
 if (diff.inHours > 0)
  return "Today ${DateFormat('jm').format(d)}";
 if (diff.inMinutes > 0)
  return "${diff.inMinutes} ${diff.inMinutes == 1 ? "minute" : "minutes"} ago";
 return "just now";
}

Add This Package --> intl: ^0.17.0


Time Show Example (Today 8:29 PM)
2g32fytz

2g32fytz9#

@Alex289答案的变体

extension DateHelpers on DateTime {

  String toTimeAgoLabel({bool isIntervalNumericVisible = true}) {
    final now = DateTime.now();
    final durationSinceNow = now.difference(this);

    final inDays = durationSinceNow.inDays;
    if (inDays >= 1) {
      return (inDays / 7).floor() >= 1
          ? isIntervalNumericVisible ? '1 week ago' : 'Last week'
          : inDays >= 2
              ? '$inDays days ago'
              : isIntervalNumericVisible
                  ? '1 day ago'
                  : 'Yesterday';
    }

    final inHours = durationSinceNow.inHours;
    if (inHours >= 1) {
      return inHours >= 2
          ? '$inHours hours ago'
          : isIntervalNumericVisible
              ? '1 hour ago'
              : 'An hour ago';
    }

    final inMinutes = durationSinceNow.inMinutes;
    if (inMinutes >= 2) {
      return inMinutes >= 2
          ? '$inMinutes minutes ago'
          : isIntervalNumericVisible
              ? '1 minute ago'
              : 'A minute ago';
    }

    final inSeconds = durationSinceNow.inSeconds;
    return inSeconds >= 3 ? '$inSeconds seconds ago' : 'Just now';
  }
}

相关问题