javatime

How can I calculate a time difference in Java?


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


Solution

  • 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.