Pages

12 February, 2013

Date and Time Difference in Java


Classes Which are used in the Program for calculating the time difference...


java.text 
Class SimpleDateFormat

java.lang.Object
  extended byjava.text.Format
      extended byjava.text.DateFormat
          extended byjava.text.SimpleDateFormat
All Implemented Interfaces:
Cloneable, Serializable
 

java.util 
Class Date

java.lang.Object
  extended by java.util.Date
All Implemented Interfaces:
Serializable, Cloneable, Comparable<Date>
Direct Known Subclasses:
Date, Time, Timestamp
 
 

Here the sample code for getting the time difference HH:MM:SS Format...

 
package com.sana.test.date;

import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeDiffTest {

    public static void main(String[] args) {

        String startDate = "01/23/2013 06:34:44";
        String endDate= "01/24/2013 08:22:57";

        //HH converts hour in 24 hours format (0-23), day calculation

        SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

        Date d1 = null;
        Date d2 = null;

        try {
            d1 = format.parse(startDate );
            d2 = format.parse(endDate);

            //in milliseconds
            long diff = d2.getTime() - d1.getTime();

            long diffSeconds = diff / 1000 % 60;
            long diffMinutes = diff / (60 * 1000) % 60;
            long diffHours = diff / (60 * 60 * 1000) % 24;
            long diffDays = diff / (24 * 60 * 60 * 1000);

            System.out.print(diffDays + " days, ");
            System.out.print(diffHours + " hours, ");
            System.out.print(diffMinutes + " minutes, ");
            System.out.print(diffSeconds + " seconds.");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
 
 

THANKS 

SANA



 
 

1 comment: