像HH:mm:ss一样格式化持续时间 [英] Formatting a Duration like HH:mm:ss
本文介绍了像HH:mm:ss一样格式化持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种很好的方式可以以诸如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屋!
查看全文