我想要像这样的时差-

"2小时28分钟前"、"几秒前"、"几分钟前"、"1分钟前"、"6小时前"、"一天前"、"一周前"、"几个月前"

我将事件发生时间作为DateTime对象.我可以用DateTime.now()得到当前时间,我想计算这2次之间的差额.我目前正在使用很多行的if Else语句来完成这项工作,比如……

if (now.year > date.year) {
      //months ago
      if ((12 - date.month) + now.month > 11) {
        return "a year ago";
      } else if ((12 - date.month) + now.month > 1) {
        return "${(12 - date.month) + now.month} months ago";
      } else if ((12 - date.month) + now.month == 1) {
        if ((getDateCountForMonth(date.month) - date.day) + now.day > 13) {
          return "a few weeks ago";
        }
...}}

Is there a better and simple way to do this? I want to output like this - "2小时28分钟前"、"几秒前"、"几分钟前"、"1分钟前"、"6小时前"、"一天前"、"一周前"、"几个月前"

推荐答案

我以前创建了一个function来计算一个项目的时间差,你可以利用这个函数.只需通过传递您想要与当前计时进行比较的DateTime字符串来调用它:

String getComparedTime(String dateTime) {
    Duration difference = DateTime.now().difference(DateTime.parse(dateTime));
    final List prefix = [
      "just now",
      "second(s) ago",
      "minute(s) ago",
      "hour(s) ago",
      "day(s) ago",
      "month(s) ago",
      "year(s) ago"
    ];
    if (difference.inDays == 0) {
      if (difference.inMinutes == 0) {
        if (difference.inSeconds < 20) {
          return (prefix[0]);
        } else {
          return ("${difference.inSeconds} ${prefix[1]}");
        }
      } else {
        if (difference.inMinutes > 59) {
          return ("${(difference.inMinutes / 60).floor()} ${prefix[3]}");
        } else {
          return ("${difference.inMinutes} ${prefix[2]}");
        }
      }
    } else {
      if (difference.inDays > 30) {
        if (((difference.inDays) / 30).floor() > 12) {
          return ("${((difference.inDays / 30) / 12).floor()} ${prefix[6]}");
        } else {
          return ("${(difference.inDays / 30).floor()} ${prefix[5]}");
        }
      } else {
        return ("${difference.inDays} ${prefix[4]}");
      }
    }
  }

Flutter相关问答推荐

如何将图像从顶部和底部半向外设置为飘动

如何更改ElevatedButton的 colored颜色 以按下它?

Flutter -使用最小高度展开

在Flutter 中压缩图片返回空

相同的Flutter 代码库,但Firebase登录适用于Web应用程序,但无法登录iOS应用程序

为什么要在值列表中两次放入空安全性

Flutter类调用另一个类中的另一个方法失败

Flutter 未处理的异常 - 对 null 值使用 Null 判断运算符

Flutter 中的区域不匹配

使用Flutter项目设置Firebase遇到困难?这些解决方案或许能帮到你!

来自服务器的数据未分配给变量

如何从 Flutter 中的 App2 远程点击 App1 中的按钮

升级到 Flutter 3.10 后,Flutter 键盘填充不起作用. Flutter 3.10 如何防止 BottomSheet 被键盘覆盖?

我怎样才能消除我的 Column 子元素之间的差距?

Flutter 应用程序在启动画面冻结(java.lang.RuntimeException:无法启动活动 ComponentInfo)

如何获得Flutter 的时差?

在 Flutter 中,您什么时候应该更喜欢Widget继承而不是组合?

Flutter 小部件中的视图和逻辑分离

参数类型Future>不能分配给参数类型Future>?

Flutter - 如何调用此函数?