How to calculate time difference in java?

后端 未结 17 1555
醉酒成梦
醉酒成梦 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 16:50

    String time1 = "16:00:00";
    String time2 = "19:00:00";
    
    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
    Date date1 = format.parse(time1);
    Date date2 = format.parse(time2);
    long difference = date2.getTime() - date1.getTime(); 
    

    Difference is in milliseconds.

    I modified sfaizs post.

提交回复
热议问题