格式化像 HH:mm:ss 这样的持续时间 [英] Formatting a Duration like HH:mm:ss

查看:33
本文介绍了格式化像 HH:mm:ss 这样的持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种好方法可以将 Duration 格式化为 hh:mm:ss 之类的格式,而无需处理时区?

Is there a good way to format a Duration in something like hh:mm:ss, without having to deal with time zones?

我试过了:

DateTime durationDate = DateTime.fromMillisecondsSinceEpoch(0);
String duration = DateFormat('hh:mm:ss').format(durationDate);

但我总是有 1 小时多的时间,在这种情况下它会说 01:00:00

But I always get 1 hour to much, in this case it would say 01:00:00

当我这样做时:

Duration(milliseconds: 0).toString();

我明白了:0:00:00.000000

推荐答案

你可以使用 Duration 并实现这个方法:

You can use Duration and implement this method:

String _printDuration(Duration duration) {
  String twoDigits(int n) => n.toString().padLeft(2, "0");
  String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
  String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
  return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
}

用法:

final now = Duration(seconds: 30);
print("${_printDuration(now)}");

这篇关于格式化像 HH:mm:ss 这样的持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆