I would like to ask what is the formula to use in our coding when we want to calculate 7384 seconds into hours, minutes and seconds? Thank you!

Printable View

- 04-30-2007, 06:41 PMyuchuangWhat is the formula?
I would like to ask what is the formula to use in our coding when we want to calculate 7384 seconds into hours, minutes and seconds? Thank you!

- 04-30-2007, 07:21 PMlevent
1 hour = 60 x 60 seconds

1 minute = 60 seconds

So you will first need to find hours by dividing your number to 60x60. Then you will divide the remaining seconds to 60 to find minutes and then you will assign remaining seconds as the seconds.

Something like this:

Code:`int x = 7384;`

int hours = 7384/(60*60);

int minutes = (7384%(60*60))/60;

int seconds = (7384%(60*60))%60;

- 04-30-2007, 08:02 PMyuchuang
Thanks! I understand now. :)

- 04-30-2007, 11:00 PMgoldhouse
If you want to have more flexibility use convert() method from TimeUnit in Java SE 6

Please have a look at the method details

Code:`convert`

public long convert(long sourceDuration,

TimeUnit sourceUnit)

Convert the given time duration in the given unit to this unit. Conversions from finer to coarser granularities truncate, so lose precision. For example converting 999 milliseconds to seconds results in 0. Conversions from coarser to finer granularities with arguments that would numerically overflow saturate to Long.MIN_VALUE if negative or Long.MAX_VALUE if positive.

For example, to convert 10 minutes to milliseconds, use: TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES)

Parameters:

sourceDuration - the time duration in the given sourceUnit

sourceUnit - the unit of the sourceDuration argument

Returns:

the converted duration in this unit, or Long.MIN_VALUE if conversion would negatively overflow, or Long.MAX_VALUE if it would positively overflow.