Formatting a Duration like HH:mm:ss

后端 未结 11 982
孤城傲影
孤城傲影 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:37

    Basen on @diegoveloper's answer, I made it an extension which is also extendible

    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";
      }
    }
    
    

提交回复
热议问题