像HH:mm:ss一样格式化持续时间

时间:2019-02-19 21:21:22

标签: dart flutter

是否有一种很好的方法可以在不处理时区的情况下以hh:mm:ss这样的格式设置Duration?

我尝试过:

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

但是我总是要花费1个小时,在这种情况下,它会显示01:00:00

当我这样做时:

Duration(milliseconds: 0).toString();

我明白了:0:00:00.000000

13 个答案:

答案 0 :(得分:10)

只需快速实施即可。

这将以[DD] d:[HH] h:[mm] m:[sssss]格式显示持续时间,并且如果忽略前导元素,则将忽略该元素,但始终会显示秒。

例如:

1d:2h:3m:4s

2h:3m:4s

3m:4s

4s

0s

  /// Returns a formatted string for the given Duration [d] to be DD:HH:mm:ss
  /// and ignore if 0.
  static String formatDuration(Duration d) {
    var seconds = d.inSeconds;
    final days = seconds~/Duration.secondsPerDay;
    seconds -= days*Duration.secondsPerDay;
    final hours = seconds~/Duration.secondsPerHour;
    seconds -= hours*Duration.secondsPerHour;
    final minutes = seconds~/Duration.secondsPerMinute;
    seconds -= minutes*Duration.secondsPerMinute;

    final List<String> tokens = [];
    if (days != 0) {
      tokens.add('${days}d');
    }
    if (tokens.isNotEmpty || hours != 0){
      tokens.add('${hours}h');
    }
    if (tokens.isNotEmpty || minutes != 0) {
      tokens.add('${minutes}m');
    }
    tokens.add('${seconds}s');

    return tokens.join(':');
  }

答案 1 :(得分:3)

您可以使用<body> <div id="body12"> <a href='#' class='articleTitle'><font size="+1">Main Category</font></a> <div class='showArticle'> <a href='#' class='commentsTitle'><font size="+1">Sub1</font></a> <div class='showComments'> <font size="+1" color="red"><b>Text1</b></font> </div><br> <a href='#' class='commentsTitle'><font size="+1">Sub2</font></a> <div class='showComments'> <font size="+1" color="red"><b>Text2</b></font> </div></div><br> <script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js' type='text/javascript'></script> </body> </html>并实现此方法:

Duration

用法:

      String _printDuration(Duration duration) {
        String twoDigits(int n) {
          if (n >= 10) return "$n";
          return "0$n";
        }

        String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
        String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
        return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
      }

答案 2 :(得分:3)

根据@diegoveloper的回答,我将其扩展为可扩展

extension DurationExtensions on Duration {
  /// Converts the duration into a readable string
  /// 05:15
  String toHoursMinutes() {
    String twoDigitMinutes = _toTwoDigits(this.inMinutes.remainder(60));
    return "${_toTwoDigits(this.inHours)}:$twoDigitMinutes";
  }

  /// Converts the duration into a readable string
  /// 05:15:35
  String toHoursMinutesSeconds() {
    String twoDigitMinutes = _toTwoDigits(this.inMinutes.remainder(60));
    String twoDigitSeconds = _toTwoDigits(this.inSeconds.remainder(60));
    return "${_toTwoDigits(this.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
  }

  String _toTwoDigits(int n) {
    if (n >= 10) return "$n";
    return "0$n";
  }
}

答案 3 :(得分:3)

详细说明其他答案,以下是也可以格式化日期的实现:

extension DurationFormatter on Duration {
  /// Returns a day, hour, minute, second string representation of this `Duration`.
  ///
  ///
  /// Returns a string with days, hours, minutes, and seconds in the
  /// following format: `dd:HH:MM:SS`. For example,
  ///
  ///   var d = new Duration(days:19, hours:22, minutes:33);
  ///    d.dayHourMinuteSecondFormatted();  // "19:22:33:00"
  String dayHourMinuteSecondFormatted() {
    this.toString();
    return [
      this.inDays,
      this.inHours.remainder(24),
      this.inMinutes.remainder(60),
      this.inSeconds.remainder(60)
    ].map((seg) {
      return seg.toString().padLeft(2, '0');
    }).join(':');
  }
}

不幸的是,intlDateFormat类没有帮助:它将Duration的格式标记为未实现:

formatDuration(DateTime reference) → String
NOT YET IMPLEMENTED. [...]

答案 4 :(得分:2)

这是另一个版本。这时都是首选,但我喜欢它干而且不需要函数声明(包装函数显然是可选的),尽管它肯定有点繁重。

紧凑

view.layer.maskedCorners = cornersToMask

格式化版本

String formatTime(double time) {
    Duration duration = Duration(milliseconds: time.round());
    return [duration.inHours, duration.inMinutes, duration.inSeconds].map((seg) => seg.remainder(60).toString().padLeft(2, '0')).join(':');
}

答案 5 :(得分:2)

HH:mm:ss获取Duration的最短,最优雅,最可靠的方法是:

format(Duration d) => d.toString().split('.').first.padLeft(8, "0");

用法示例:

main() {
  final d1 = Duration(hours: 17, minutes: 3);
  final d2 = Duration(hours: 9, minutes: 2, seconds: 26);
  final d3 = Duration(milliseconds: 0);
  print(format(d1)); // 17:03:00
  print(format(d2)); // 09:02:26
  print(format(d3)); // 00:00:00
}

答案 6 :(得分:2)

定义此:

extension on Duration {
  String format() => '$this'.split('.')[0].padLeft(8, '0');
}

用法:

String time = Duration(seconds: 3661).format(); // 01:01:01

答案 7 :(得分:2)

format(Duration d) => d.toString().split('.').first.padLeft(8, "0");

main() {
  final d1 = Duration(hours: 17, minutes: 3);
  final d2 = Duration(hours: 9, minutes: 2, seconds: 26);
  final d3 = Duration(milliseconds: 0);
  print(format(d1)); // 17:03:00
  print(format(d2)); // 09:02:26
  print(format(d3)); // 00:00:00
}

答案 8 :(得分:0)

您可以自己开始创建格式,快来看看吧:

String sDuration="${duration.inHours}:${duration.inMinutes}:${(duration.inSeconds % 60)}

答案 9 :(得分:0)

您可以使用此:

print('${duration.inHours.toString().padLeft(2, '0')}:
${duration.inMinutes.remainder(60).toString().padLeft(2, '0')}:
${duration.inSeconds.remainder(60).toString().padLeft(2, '0')}');

答案 10 :(得分:0)

我更喜欢将毫秒视为自己的单位,而不是毫秒的子单位 其他的东西。在这种情况下,它将具有0-999的值,因此您将 想要像我在其他答案中看到的那样填充三个而不是两个。这是 一个实现:

import {  useLocation } from 'react-router-dom';

 const App = () => {
  const location = useLocation();
  console.log(location.pathname)  
  //...
};

https://api.dart.dev/dart-core/Duration-class.html

答案 11 :(得分:0)

我认为最简单的方法

String get refactoredDuration{
    return Duration(seconds: duration).toString().split('.')[0];
  }

答案 12 :(得分:-1)

要以可移植的方式执行此操作,请考虑intl软件包DateFormat类:https://pub.dartlang.org/documentation/intl/latest/intl/DateFormat-class.html