Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
978 views
in Technique[技术] by (71.8m points)

datetime - Java: convert seconds into day, hour, minute and seconds using TimeUnit

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

  1. Day calculation is correct, it does not require explanation.
  2. TimeUnit.SECONDS.toHours(seconds) will give you direct conversion from seconds to hours without consideration for days you have already calculated. Minus the hours for days you already got i.e, day*24. You now got remaining hours.
  3. Same for minute and second. You need to minus the already got hour and minutes respectively.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...