Formatting a Duration like HH:mm:ss

后端 未结 11 988
孤城傲影
孤城傲影 2020-12-05 22:53

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

I tried this:

DateTime durationDate = Da         


        
11条回答
  •  天涯浪人
    2020-12-05 23:33

    Elaborating on other answers, here is an implementation that also formats days:

    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(':');
      }
    }
    

    Unfortunately the intl package DateFormat class does not help: it marks the format of a Duration as not implemented:

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

提交回复
热议问题