javacodex.com
Java Examples
Java Examples
memu home questions

Calculate Time Difference Between Two Timestamps

This example calculates the difference between two timestamps.

Source: (TimeDifference.java)

import java.sql.Timestamp;
import java.util.Calendar;
 
public class TimeDifference {
 
  public static void main(String[] args) {
 
    java.util.Date date = new java.util.Date();
    Timestamp timestamp1 = new Timestamp(date.getTime());
 
     // create a calendar and assign it the same time
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(timestamp1.getTime());
 
    // add a bunch of seconds to the calendar 
    cal.add(Calendar.SECOND, 98765);
 
    // create a  second time stamp
    Timestamp timestamp2 = new Timestamp(cal.getTime().getTime());
 
    // get time difference in seconds
    long milliseconds = timestamp2.getTime() - timestamp1.getTime();
    int seconds = (int) milliseconds / 1000;
 
    // calculate hours minutes and seconds
    int hours = seconds / 3600;
    int minutes = (seconds % 3600) / 60;
    seconds = (seconds % 3600) % 60;
 
 
    System.out.println("timestamp1: " + timestamp1);
    System.out.println("timestamp2: " + timestamp2);
 
    System.out.println("Difference: ");
    System.out.println(" Hours: " + hours);
    System.out.println(" Minutes: " + minutes);
    System.out.println(" Seconds: " + seconds);
  }
}
 
 

Output:

$ java TimeDifference
timestamp1: 2015-10-07 06:51:26.778
timestamp2: 2015-10-08 10:17:31.778
Difference: 
 Hours: 27
 Minutes: 26
 Seconds: 5

Questions answered by this page:

Calculate the difference between two timstamps. How to find the duration between 2 timestamps? Calculate duration between two timestamps in java. Calculate time difference between two timestamps in java.

Related Examples:


Contact: javacodex@yahoo.com