How to calculate time difference in java?

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

    import java.util.Date;
    ...
    Date d1 = new Date();
    ...
    ...
    Date d2 = new Date();
    System.out.println(d2.getTime()-d1.getTime()); //gives the time difference in milliseconds. 
    System.out.println((d2.getTime()-d1.getTime())/1000); //gives the time difference in seconds.
    

    and, to show in a nicer format, you can use:

        DecimalFormat myDecimalFormatter = new DecimalFormat("###,###.###");
        System.out.println(myDecimalFormatter.format(((double)d2.getTime()-d1.getTime())/1000));
    

提交回复
热议问题