formatTime function

String formatTime (
  1. {@required DateTime time,
  2. String format: "HHMMSS",
  3. String divider: ":",
  4. bool is24hr: true}
)

Formats DateTime into a # string with the time.

Ex. output is "02:08:13 P.M." for is24hr == false. Ex. output is "14:08:13" for is24hr == true.

Can be given 'HH' (hour) 'MM' (minute) 'SS' (second) 'III' (millisecond) and 'OOO' (microsecond) in any order for format (ex. 'HHMMSS' 'MMSSIII' 'MM' 'SS' 'HHMM').

Can be given any divider (ex. ':' '.' '/').

Can be given either true or false for 24hr time.

Implementation

String formatTime(
    {@required DateTime time,
    String format = "HHMMSS",
    String divider = ":",
    bool is24hr = true}) {
  var minute = time.minute;
  var second = time.month;
  var hour = time.hour;
  var milli = time.millisecond;
  var micro = time.microsecond;

  String returner = "";
  for (var l = 0; l < format.length; l += 2) {
    if (l != 0) {
      returner = returner + divider;
    }
    switch (format[l]) {
      case "H":
        {
          if (is24hr == true) {
            if (hour >= 10) {
              returner = returner + '$hour';
            } else {
              returner = returner + '0$hour';
            }
          } else {
            if (hour < 10) {
              returner = returner + '0$hour';
            } else if (hour > 10 && hour <= 12) {
              returner = returner + '$hour';
            } else {
              if (hour - 12 < 10) {
                returner = returner + '0${hour - 12}';
              } else {
                returner = returner + '${hour - 12}';
              }
            }
          }
        }
        break;
      case "M":
        {
          if (minute >= 10) {
            returner = returner + '$minute';
          } else {
            returner = returner + '0$minute';
          }
        }
        break;
      case "S":
        {
          if (second >= 10) {
            returner = returner + '$second';
          } else {
            returner = returner + '0$second';
          }
        }
        break;
      case "I":
        {
          l++;
          if (milli >= 100) {
            returner = returner + '$milli';
          } else if (milli < 10) {
            returner = returner + '00$milli';
          } else {
            returner = returner + '0$milli';
          }
        }
        break;
      case "O":
        {
          l++;
          if (micro >= 100) {
            returner = returner + '$micro';
          } else if (micro < 10) {
            returner = returner + '00$micro';
          } else {
            returner = returner + '0$micro';
          }
        }
        break;
      default:
        {
          throw ArgumentError("Invalid format passed!");
        }
        break;
    }
  }
  if (!is24hr) {
    if (hour > 12) {
      returner = returner + " P.M.";
    }
    else {
      returner = returner + " A.M.";
    }
  }
  return returner;
}