How to calculate time difference in java?

后端 未结 17 1587
醉酒成梦
醉酒成梦 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:11

    String start = "12:00:00";
    String end = "02:05:00";
    
    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); 
    
    Date date1 = format.parse(start);
    
    Date date2 = format.parse(end);
    
    long difference = date2.getTime() - date1.getTime(); 
    
    int minutes = (int) TimeUnit.MILLISECONDS.toMinutes(difference);
    
    if(minutes<0)minutes += 1440; 
    

    Now minutes will be the correct duration between two time (in minute).

提交回复
热议问题