Convert seconds value to hours minutes seconds?

rabbitt picture rabbitt · May 25, 2011 · Viewed 233.9k times · Source

I've been trying to convert a value of seconds (in a BigDecimal variable) to a string in an editText like "1 hour 22 minutes 33 seconds" or something of the kind.

I've tried this:

String sequenceCaptureTime = "";
BigDecimal roundThreeCalc = new BigDecimal("0");
BigDecimal hours = new BigDecimal("0");
BigDecimal myremainder = new BigDecimal("0");
BigDecimal minutes = new BigDecimal("0");
BigDecimal seconds = new BigDecimal("0");
BigDecimal var3600 = new BigDecimal("3600");
BigDecimal var60 = new BigDecimal("60");

(I have a roundThreeCalc which is the value in seconds so I try to convert it here.)

hours = (roundThreeCalc.divide(var3600));
myremainder = (roundThreeCalc.remainder(var3600));
minutes = (myremainder.divide(var60));
seconds = (myremainder.remainder(var60));
sequenceCaptureTime =  hours.toString() + minutes.toString() + seconds.toString();

Then I set the editText to sequnceCaptureTime String. But that didn't work. It force closed the app every time. I am totally out of my depth here, any help is greatly appreciated. Happy coding!

Answer

Geobits picture Geobits · May 25, 2011

Is it necessary to use a BigDecimal? If you don't have to, I'd use an int or long for seconds, and it would simplify things a little bit:

hours = totalSecs / 3600;
minutes = (totalSecs % 3600) / 60;
seconds = totalSecs % 60;

timeString = String.format("%02d:%02d:%02d", hours, minutes, seconds);

You might want to pad each to make sure they're two digit values(or whatever) in the string, though.