Skip to content

Instantly share code, notes, and snippets.

@AlexV525
Created August 26, 2020 06:45
Show Gist options
  • Select an option

  • Save AlexV525/c4f00ad68788fd8ac17b690e51285845 to your computer and use it in GitHub Desktop.

Select an option

Save AlexV525/c4f00ad68788fd8ac17b690e51285845 to your computer and use it in GitHub Desktop.
Split duration to string
void main() {
final Duration duration = Duration(hours: 12, minutes: 34, seconds: 56);
print(duration.splitToString(':'));
}
extension SplitDurationExtension on Duration {
String splitToString(
String divider, {
bool shouldPadLeft = false,
String padWith = '0',
}) {
final int hour = this.inHours;
final int minute = this.inMinutes - Duration(hours: hour).inMinutes;
final int second =
this.inSeconds - Duration(hours: hour, minutes: minute).inSeconds;
final String result =
'${shouldPadLeft ? hour.toString().padLeft(2, padWith) : hour}$divider'
'${shouldPadLeft ? minute.toString().padLeft(2, padWith) : minute}$divider'
'${shouldPadLeft ? second.toString().padLeft(2, padWith) : second}';
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment