Java:使用 TimeUnit 将秒转换为天、小时、分钟和秒

2022-08-31 20:03:48

我正在使用TimeStamp类将秒转换为天,小时,分钟,秒。我用了下面的代码

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

    }

但我没有得到正确的结果。例如,当我调用此方法时,它会给我结果,而不是.calculateTime(3600)Day 0 Hour 1 Minute 60 Seconds 3540Day 0 Hour 1 Minute 0 Seconds 0

我的逻辑有什么问题?请帮帮我。


答案 1

它应该像

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

编辑解释:

  1. 天计算是正确的,它不需要解释。
  2. TimeUnit.SECONDS.toHours(秒)将为您提供从秒到小时的直接转换,而不考虑您已经计算的天数。减去您已经获得的天数的小时数,即第*24天。你现在有剩余的时间。
  3. 分钟和秒相同。您需要分别减去已经获得的小时和分钟。

答案 2

你可以这样做只使用: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);
}

或者稍微短一点,但可能不那么直观

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