toTimeFormat method

String toTimeFormat({
  1. bool? showDays,
  2. bool? showHours,
  3. bool? showMilli,
})

This method will convert a int number into a String using date format.

Types:

  • Days
  • Hours
  • Minutes
  • Seconds
  • Milliseconds

Important:

  • If none of the parameters is true the format will be Minute:Seconds.

Examples:

1-

String convert = 100000000.toTimeFormat(showDays: true, showMilli: true);
print(convert); //Format: 02:03:46:40:40

2-

String convert = 100000000.toTimeFormat(showDays: false, showMilli: false);
print(convert); //Format: 46:40

3-

String convert = 100000000.toTimeFormat(showHours: true);
print(convert); //Format: 03:46:40

Implementation

String toTimeFormat({
  bool? showDays,
  bool? showHours,
  bool? showMilli,
}) {
  Duration time = Duration(milliseconds: this);
  String twoDigits(int n) => n.toString().padLeft(2, "0");
  String twoDigitHours = twoDigits(time.inHours.remainder(24));
  String twoDigitMinutes = twoDigits(time.inMinutes.remainder(60));
  String twoDigitSeconds = twoDigits(time.inSeconds.remainder(60));
  String twoDigitMilli = twoDigits(time.inMilliseconds.remainder(60));
  String defaultValue = "$twoDigitMinutes:$twoDigitSeconds";

  if (showMilli != null && showMilli)
    defaultValue = defaultValue + ":$twoDigitMilli";
  if (showHours != null && showHours)
    defaultValue = "$twoDigitHours:" + defaultValue;
  if (showDays != null && showDays) {
    showHours = true;
    defaultValue = "${time.inDays}:$twoDigitHours:" + defaultValue;
  }
  return defaultValue;
}