flutter - 如何在 Flutter 中像 Youtube 一样显示时间
问题描述
我正在编写一个颤振应用程序来使用Youtube API V3克隆一些 Youtube 功能。
该应用程序从 youtube video 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)
推荐阅读
- php - laravel中唯一的两列
- database - 是否可以在 CakePHP 3 的会话表中保存附加数据?
- python - Python - 基于 UUID 的分片
- ruby-on-rails - 在我的 Ruby on Rails 代码中出现“未定义的方法”错误
- python - python生成器垃圾收集
- firebase - 在 Firebase 中使用函数向(分析)受众发送推送通知
- swift - 日期未获取手机 Swift 4 的当前时间
- javascript - 如何使用 PATRICK SPRINGSTUBBE jQuery 多选插件进行单选
- excel - 过滤搜索并与单元格比较的公式
- assembly - ASM - TLINK 无符号表