Java how to calculate time differences

前端 未结 2 574
悲&欢浪女
悲&欢浪女 2021-01-23 03:42

How can I calculate the time differences in 24 hour if the user input is 2255 and 2305 the output should be 10 minutes. I got an idea is to separate the input to 2 parts, 2 digi

2条回答
  •  野性不改
    2021-01-23 04:26

        String time1 = "2255";
        String time2 = "2305";
    
        SimpleDateFormat format = new SimpleDateFormat("HHmm");
        Date date1 = format.parse(time1);
        Date date2 = format.parse(time2);
        long difference = date2.getTime() - date1.getTime();        
    

    difference is in millis you can convert it to any unit or you can use DurationFormatUtils from apache-commons to pretty format it.

    System.out.println("Duration: "+DurationFormatUtils.formatDuration(difference, "HH:mm"));
    

    apache commons has really nice utility functions, apache-commons (lang)

提交回复
热议问题