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.
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.
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.
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.
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With