I am using TimeStamp class to convert seconds into Day,Hours,Minutes,Seconds. I used following code
public static void calculateTime(long seconds) { int day = (int)TimeUnit.SECONDS.toDays(seconds); long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.SECONDS.toHours(TimeUnit.SECONDS.toDays(seconds)); long minute = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.SECONDS.toMinutes(TimeUnit.SECONDS.toHours(seconds)); long second = TimeUnit.SECONDS.toSeconds(seconds) - TimeUnit.SECONDS.toSeconds(TimeUnit.SECONDS.toMinutes(seconds)); System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second); }
But I am not getting right result. For example when I called this method as calculateTime(3600)
it gives me the result as Day 0 Hour 1 Minute 60 Seconds 3540
instead of Day 0 Hour 1 Minute 0 Seconds 0
.
What is the wrong with my logic? Please help me.
int seconds = (totalSeconds % 60); int minutes = (totalSeconds % 3600) / 60; int hours = (totalSeconds % 86400) / 3600; int days = (totalSeconds % (86400 * 30)) / 86400; First line - We get the remainder of seconds when dividing by number of seconds in a minutes.
To convert seconds to HH:MM:SS :Multiply the seconds by 1000 to get milliseconds. Pass the milliseconds to the Date() constructor. Use the toISOString() method on the Date object.
It should be like
int day = (int)TimeUnit.SECONDS.toDays(seconds); long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24); long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60); long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
EDIT Explanation:
You can do like this to only use TimeUnit
:
public static void calculateTime(long seconds) { int day = (int) TimeUnit.SECONDS.toDays(seconds); long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.DAYS.toHours(day); long minute = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.DAYS.toMinutes(day) - TimeUnit.HOURS.toMinutes(hours); long second = TimeUnit.SECONDS.toSeconds(seconds) - TimeUnit.DAYS.toSeconds(day) - TimeUnit.HOURS.toSeconds(hours) - TimeUnit.MINUTES.toSeconds(minute); System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second); }
or the slightly shorter but maybe not as intuitive
public static void calculateTime(long seconds) { int day = (int) TimeUnit.SECONDS.toDays(seconds); long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.DAYS.toHours(day); long minute = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(seconds)); long second = TimeUnit.SECONDS.toSeconds(seconds) - TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(seconds)); System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With