How to calculate time difference in java?

后端 未结 17 1401
醉酒成梦
醉酒成梦 2020-11-22 16:33

I want to subtract two timeperiods say 16:00:00 from 19:00:00. Is there any java function for this? The results can be in milliseconds, seconds, or minutes.

17条回答
  •  死守一世寂寞
    2020-11-22 17:01

    public class timeDifference {
    
    public static void main(String[] args) {
    
        try {
    
            Date startTime = Calendar.getInstance().getTime();
            Thread.sleep(10000);
            Date endTime = Calendar.getInstance().getTime();
    
            long difference = endTime.getTime() - startTime.getTime();
    
            long differenceSeconds = difference / 1000 % 60;
            long differenceMinutes = difference / (60 * 1000) % 60;
            long differenceHours = difference / (60 * 60 * 1000) % 24;
            long differenceDays = difference / (24 * 60 * 60 * 1000);
    
            System.out.println(differenceDays + " days, ");
            System.out.println(differenceHours + " hours, ");
            System.out.println(differenceMinutes + " minutes, ");
            System.out.println(differenceSeconds + " seconds.");
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    }

提交回复
热议问题