Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert seconds to mm:ss in dart

Tags:

flutter

dart

I want to convert seconds to minutes and seconds in HH:SS format but my logic don't give me what I want.

  static double toMin (var value){
            return (value/60);
          }

I also want to be able to add the remainder to the minutes value because sometimes my division gives me a seconds value more that 60 which is not accurate

like image 265
custom apps Avatar asked Sep 06 '25 03:09

custom apps


1 Answers

The Duration class can do most of the work for you.

var minutes = Duration(seconds: seconds).inMinutes;

You could generate a String in a mm:ss format by doing:

String formatDuration(int totalSeconds) {
  final duration = Duration(seconds: totalSeconds);
  final minutes = duration.inMinutes;
  final seconds = totalSeconds % 60;

  final minutesString = '$minutes'.padLeft(2, '0');
  final secondsString = '$seconds'.padLeft(2, '0');
  return '$minutesString:$secondsString';
}

That said, I recommend against using a mm:ss format since, without context, it's unclear whether "12:34" represents 12 minutes, 34 seconds or 12 hours, 34 minutes. I suggest instead using 12m34s, which is unambiguous.

like image 101
jamesdlin Avatar answered Sep 07 '25 22:09

jamesdlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!