formatDurationToStr static method

String formatDurationToStr(
  1. Duration duration, {
  2. MyFormatDurationType_e type = MyFormatDurationType_e.hhMMSS,
  3. MySeparatorType_e separator = MySeparatorType_e.Symbol,
})

将Duration转HH:MM:SS格式的字符串

Implementation

static String formatDurationToStr(
  Duration duration, {
  MyFormatDurationType_e type = MyFormatDurationType_e.hhMMSS,
  MySeparatorType_e separator = MySeparatorType_e.Symbol,
}) {
  String hours = "", minutes = "", seconds = "";
  switch (type) {
    case MyFormatDurationType_e.hhMMSS:
      if (duration.inHours > 0) {
        hours = duration.inHours.toString().padLeft(0, '2');
      }
      minutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0');
      seconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0');
      break;
    case MyFormatDurationType_e.HHMMSS:
      hours = duration.inHours.toString().padLeft(2, '0');
      minutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0');
      seconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0');
      break;
    case MyFormatDurationType_e.HHMM:
      hours = duration.inHours.toString().padLeft(2, '0');
      minutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0');
      break;
    case MyFormatDurationType_e.AutoHM:
      if (duration.inHours > 0) {
        hours = duration.inHours.toString();
      }
      final mm = duration.inMinutes.remainder(60);
      if (mm > 0) {
        minutes = mm.toString();
      }
    case MyFormatDurationType_e.MMSS:
      minutes = duration.inMinutes.toString().padLeft(2, '0');
      seconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0');
  }
  String restr = "";
  switch (separator) {
    case MySeparatorType_e.Char:
      if (hours.isNotEmpty) {
        restr += "$hours小时";
      }
      if (minutes.isNotEmpty) {
        restr += "$minutes分钟";
      }
      if (seconds.isNotEmpty) {
        restr += "$seconds秒";
      }
    case MySeparatorType_e.Symbol:
      if (hours.isNotEmpty) {
        restr += hours;
      }
      if (minutes.isNotEmpty) {
        if (restr.isNotEmpty) {
          restr += ":";
        }
        restr += minutes;
      }
      if (seconds.isNotEmpty) {
        if (restr.isNotEmpty) {
          restr += ":";
        }
        restr += seconds;
      }
  }
  return restr;
}