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

后端 未结 8 1765
我寻月下人不归
我寻月下人不归 2020-12-08 06:25

I am using TimeStamp class to convert seconds into Day,Hours,Minutes,Seconds. I used following code

public static void calculateTime(long seconds) {
                 


        
8条回答
  •  囚心锁ツ
    2020-12-08 06:55

    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);
    }
    

提交回复
热议问题