Sxn*_*ome 5 youtube-api datetime-format flutter
我正在编写一个 flutter 应用程序来使用Youtube API V3克隆一些 Youtube 功能。
该应用程序从 YouTube 视频 API获取字符串形式的视频时间戳
每个时间戳都具有以下格式:
YYYY-MM-DDTHH:MM:SSZ
一个例子是:
2020-07-12T20:42:19Z
我想以文本形式显示:
Sxn*_*ome 13
我在 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';
}
}
Run Code Online (Sandbox Code Playgroud)
然后以文字方式调用:
StringExtension.displayTimeAgoFromTimestamp(video.timestamp)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5160 次 |
| 最近记录: |