0

I'm working on a code converting huge numbers, such as 9999 to 2:46:39 into this format HH:MM:SS. I do understand how to get 2 hour and kind of on 46 minutes, but not so much with 39 seconds. Can anyone please this explain this to me? When I tried a different number like 4555 seconds I get 1:15:55. I understand the hour part, but now I don't on 15 minutes and 55 seconds. I think only minutes and seconds are the only things that I'm not sure of.

I'm using % to get the remainder, but when I divide them 60, especially for 4555 I don't see any 15 or 55 seconds as a remainder when using normal division.

int min = ttlNumSec % MIN60; int sec = ttlNumSec % MIN60;

Appreciate any help.

Edit: Thank you so much to all who replied and showing another ways of getting them :D

  • 2
    `9999 % 60 = 39`, `9999 / 60 = 166`, `166 % 60 = 46`, `166 / 60 = 2`. – Johannes Kuhn Sep 22 '19 at 11:03
  • Possible duplicate of [Convert seconds value to hours minutes seconds?](https://stackoverflow.com/questions/6118922/convert-seconds-value-to-hours-minutes-seconds) Please search for more. – Ole V.V. Sep 23 '19 at 07:25

2 Answers2

4

Given a number of seconds ttlNumSec, you can get how many hours it is by:

ttlNumSec / 3600

3600 is the number of seconds in an hour.

You can get the number of minutes by:

ttlNumSec % 3600 / 60

60 is the number of seconds in a minute. Why do ttlNumSec % 3600 first? Because that is equal to the number of seconds that is not enough to form another whole hour, and you want to get how many minutes that is.

To get the seconds, do:

ttlNumSec % 60

Java 9's Duration class actually has all these calculations built in, so you don't need to calculate them:

Duration d = Duration.ofSeconds(ttlNumSec);
int hours = d.toHours();
int minutes = d.toMinutesPart();
int seconds = d.toSecondsPart();
Sweeper
  • 213,210
  • 22
  • 193
  • 313
0
long time = 1536259;

return (new SimpleDateFormat("mm:ss:SSS")).format(new Date(time))

Output:

25:36:259

Willem
  • 992
  • 6
  • 13
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Also your code will give incorrect results on most JVMs. – Ole V.V. Sep 23 '19 at 07:24
  • Also in some time zones it will give incorrect results. When one day you run your code on a computer in Nepal or India and it suddenly gives an incorrect result, you may have a very hard time to find out why. Furthermore it doesn’t detect overflow (more than 60 minutes) but just tacitly throws away the hours. – Ole V.V. Sep 27 '19 at 08:10