Format Duration - Timer

Asked

Viewed 1,014 times

0

I am trying to format in Dart/Flutter the timer a certain time elapsed, whose code:

Duration _tempo = new Duration();

Text('Tempo: ${_tempo.inHours}:${_tempo.inMinutes}:${_tempo.inSeconds}'),

The result of the above line is:

  • Time: 1:2:65

Saying it’s been an hour, two minutes and five seconds.

The result I need would be: hh:nn:ss (Hour - Minute - Second) with two digits for each, with the seconds zeroing 60 by 60, which in the example above would be:

  • Time: 01:02:05

But I couldn’t do it, I couldn’t find any material that would help me in this sense, if anyone could help me I would be very grateful. Thank you.

1 answer

0


By using inMinutes and inSeconds methods you are only returning the total value of that time period in minutes and seconds respectively.

var d = Duration(hours: 1, minutes: 2, seconds: 65);

d.inHours -> 1

d.inMinutes -> 63

d.inSeconds -> 3785

It is then necessary a simple mathematical operation to convert these values in minutes and seconds, being simply the division of the value by 60, and recovering the rest.

inMinutes -> 63 / 60 -> Rest = 3

inSeconds -> 3785 / 60 -> Rest = 5

The object int in Dart has a method that takes just this rest of the division, the remainder(). With this just a utility method that adds a 0 to the left if the value is less than 10:

void main() {
  Duration d = Duration(hours: 1, minutes: 2, seconds: 65); // 1:3:5

  print('${d.inHours}:${d.inMinutes}:${d.inSeconds}');
  // 1:63:3785

  int hour = d.inHours;
  int remainderMinutes = d.inMinutes.remainder(60);
  int remainderSeconds = d.inSeconds.remainder(60);
  print('${addZero(hour)}:${addZero(remainderMinutes)}:${addZero(remainderSeconds)}');
  // 01:03:05

  String sHour = hour.toString();
  String sRemainderMinutes = remainderMinutes.toString();
  String sRemainderSeconds = remainderSeconds.toString();
  print('${sHour.padLeft(2, '0')}:${sRemainderMinutes.padLeft(2, '0')}:${sRemainderSeconds.padLeft(2, '0')}');
  // 01:03:05
}

String addZero(int value) {
  return value < 10 ? "0$value" : "$value";
}

Another alternative shown in the above code, rather than using the addZero, is to convert the value to String and use precisely the method padLeft() that adds some other String to the left of the original if it is smaller than the size passed.

Testing on the Dartpad

the/

  • Thank you very much Julio. Excellent!!! thank you very much.

  • @Clarismilton helped himself, put the answer as correct/accepted :)

  • I couldn’t put the answer as correct/accepted... sorry. but I couldn’t find where I do it.

  • @Clarismilton just click on the symbol here on the left of the question (<===). Changing from gray to green. If in doubt: https://answall.com/help/someone-answers or https://pt.meta.stackoverflow.com/a/1079

Browser other questions tagged

You are not signed in. Login or sign up in order to post.