Java finding difference between times

前端 未结 4 1831
感情败类
感情败类 2020-12-20 06:10

i have some problem while finding difference between times, if i try to find difference in todays time (say t1 = \"08:00:00\" and t2 = \"10:00:00\" then it is giving correct

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-20 07:09

    Any date/time manipulation/calculation should be done though the use of well defined and tested APIs like Java 8's Time API or Joda Time

    Java 8

    public class TestTime {
    
        public static void main(String[] args) {
            // Because of the ability for the time to roll over to the next
            // day, we need the date component to make sense of it, for example
            // 24:00 is actually 00:00 of the next day ... joy
            LocalDateTime t1 = LocalTime.of(20, 00).atDate(LocalDate.now());
            LocalDateTime t2 = LocalTime.of(12, 00).atDate(LocalDate.now());
            LocalDateTime t3 = LocalTime.MIDNIGHT.atDate(LocalDate.now()).plusDays(1);
    
            if (t1.isAfter(t2)) {
                System.out.println("Before");
                Duration duration = Duration.between(t2, t3);
                System.out.println(format(duration));
            } else {
                System.out.println("After");
                Duration duration = Duration.between(t2, t1);
                System.out.println(format(duration));
            }
        }
    
        public static String format(Duration duration) {
            long hours = duration.toHours();
            duration = duration.minusHours(hours);
    
            return String.format("%02d hours %02d minutes", hours, duration.toMinutes());
        }
    
    }
    

    Which outputs

    12 hours 00 minutes
    

    The question I can't seem to answer in your code is why you did this s4 = s2+s3;, basically adding 12:00 to 24:00

提交回复
热议问题