DEV Community

loading...
Cover image for Convert Integer value to Hour:Minute:Seconds in dart

Convert Integer value to Hour:Minute:Seconds in dart

Opeyemi Noah
Software Developer, Flutter Engineer, love to build and try new things...
・1 min read

As a developer, there are times that you 'll need to convert a integer values to time remaining, It could be during the course of using Stream or something else.

Below is a good approach to handle the situation

Not so fast,
Alt text of image
To understand the code below you need to understand some basic time conversion.

1. one(1) hour =3600 seconds

Definitely to convert let's say 2 hours to seconds we 'll have 2*3600 = 7200 seconds

2. one(1) minute = 60 seconds

Definitely to convert 2minutes to seconds we 'll have
2*60 =120 seconds

3. one(1) seconds = 1 seconds

String intToTimeLeft(int value) {
  int h, m, s;

  h = value ~/ 3600;

  m = ((value - h * 3600)) ~/ 60;

  s = value - (h * 3600) - (m * 60);

  String result = "$h:$m:$s";

  return result;
}
Enter fullscreen mode Exit fullscreen mode

Output


0:0:0
Enter fullscreen mode Exit fullscreen mode

And if you decide to go with one with more muscle

String intToTimeLeft(int value) {
  int h, m, s;

  h = value ~/ 3600;

  m = ((value - h * 3600)) ~/ 60;

  s = value - (h * 3600) - (m * 60);

  String hourLeft = h.toString().length < 2 ? "0" + h.toString() : h.toString();

  String minuteLeft =
      m.toString().length < 2 ? "0" + m.toString() : m.toString();

  String secondsLeft =
      s.toString().length < 2 ? "0" + s.toString() : s.toString();

  String result = "$hourLeft:$minuteLeft:$secondsLeft";

  return result;
}
Enter fullscreen mode Exit fullscreen mode

Output


00:00:00
Enter fullscreen mode Exit fullscreen mode

That wraps up everything ..See you in the next one

Discussion (2)

Collapse
pablonax profile image
Pablo Discobar

Good job! If you are interested in this topic, you can also look at my article about free vs paid Flutter templates. I'm sure you'll find something useful there, too.  - dev.to/pablonax/free-vs-paid-flutt...