How to calculate time difference in java?

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

    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class Main {
    public static void main(String[] args) throws Exception{
        String time1 = "12:00:00";
        String time2 = "12:01:00";
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        Date date1 = format.parse(time1);
        Date date2 = format.parse(time2);
        long difference = date2.getTime() - date1.getTime();
        System.out.println(difference/1000);
    }}
    

    throws exception handles parsing exceptions

提交回复
热议问题