gpt4 book ai didi

flutter - 如何在 Flutter 中像 Youtube 一样显示时间

转载 作者:行者123 更新时间:2023-12-04 15:58:49 24 4
gpt4 key购买 nike

我正在编写一个 Flutter 应用程序来使用 克隆一些 Youtube 功能Youtube API V3 .
该应用程序获取 视频时间戳作为字符串 来自 youtube 视频 API
每个时间戳具有以下格式:

YYYY-MM-DDTHH:MM:SSZ


一个例子是:

2020-07-12T20:42:19Z


我想在文本中显示:
  • 1 小时
  • 1 小时前
  • 4 周前
  • 11 个月前
  • 1年前
  • ...
  • 最佳答案

    我在 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';
    }
    }
    然后在文本中调用:
    StringExtension.displayTimeAgoFromTimestamp(video.timestamp)

    关于flutter - 如何在 Flutter 中像 Youtube 一样显示时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62873902/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com