skip to Main Content

For example i have some of the following Duration values

0:12:15.000000 // the hour is 0 so i want to display the value like mm-ss => 12:15
0:01:02.000000 // the minutes is less than 10 so i want to display the value like m-ss => 1:02
0:00:05.000000  // the minutes is 0 so i want to the value like m-ss => 0:05

i import these Duration values from video info so i don’t know what was the type of .000000 is . but i want to remove them too .

How could i handle these scenarios in best way 🙂

2

Answers


  1. Assuming you have duration object. You can define your format function something like this and use it.

      String _formatVideoDuration(Duration duration) {
        final hours = (duration.inHours);
        final minutes = (duration.inMinutes % 60);
        final ss = (duration.inSeconds % 60).toString().padLeft(2, '0');
    
        if (hours > 9) {
          return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:$ss';
        } else if (hours > 0) {
          return '${hours.toString().padLeft(1, '0')}:${minutes.toString().padLeft(2, '0')}:$ss';
        } else if (minutes > 9) {
          return '${minutes.toString().padLeft(2, '0')}:$ss';
        } else {
          return '${minutes.toString().padLeft(1, '0')}:$ss';
        }
      }
    
    Login or Signup to reply.
  2. I guess this might help

    String formatDuration(Duration duration) {
      String twoDigitMinutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0');
      String twoDigitSeconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0');
      
      if (duration.inHours == 0) {
        return '$twoDigitMinutes:$twoDigitSeconds';
      } else if (duration.inMinutes < 10) {
        return '${duration.inHours}:$twoDigitMinutes:$twoDigitSeconds';
      } else {
        return '${duration.inHours}:$twoDigitMinutes:$twoDigitSeconds';
      }
    }
    
    Duration duration = Duration(hours: 0, minutes: 12, seconds: 15);
    String formattedDuration = formatDuration(duration);
    print(formattedDuration); // prints "12:15"
    
    duration = Duration(hours: 0, minutes: 1, seconds: 2);
    formattedDuration = formatDuration(duration);
    print(formattedDuration); // prints "1:02"
    
    duration = Duration(hours: 0, minutes: 0, seconds: 5);
    formattedDuration = formatDuration(duration);
    print(formattedDuration); // prints "0:05"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search