Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate a time difference in Java?

Tags:

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.

like image 559
user607304 Avatar asked Feb 07 '11 23:02

user607304


People also ask

How do you calculate time difference?

To calculate the time difference in minutes, you need to multiply the resulting value by the total number of minutes in a day (which is 1440 or 24*60). Suppose you have a data set as shown below and you want to calculate the total number of minutes elapsed between the start and the end date.

How do you calculate duration in Java?

Find the time difference between two dates in millisecondes by using the method getTime() in Java as d2. getTime() – d1. getTime(). Use date-time mathematical formula to find the difference between two dates.

How do you manually calculate time difference?

Compute time difference manuallySubtract all end times from hours to minutes. If the start minutes is higher than the end minutes, subtract an hour from the end time hours and add 60 minutes to the end minutes. Proceed to subtract the start time minutes to the end minutes. Subtract the hours too from end to start.


2 Answers

Java 8 has a cleaner solution - Instant and Duration

Example:

import java.time.Duration; import java.time.Instant; ... Instant start = Instant.now(); //your code Instant end = Instant.now(); Duration timeElapsed = Duration.between(start, end); System.out.println("Time taken: "+ timeElapsed.toMillis() +" milliseconds"); 
like image 62
Anila Sebastian Avatar answered Oct 11 '22 02:10

Anila Sebastian


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.

like image 44
Uros K Avatar answered Oct 11 '22 01:10

Uros K