-1

Possible Duplicate:
Calculating the Difference Between Two Java Date Instances

i have two date values in two textboxes in string datatypes in HH:MM:SS format.HOw can i find difference between them and get result in HH:MM:SS?please help me...as fast as possible....!

Community
  • 1
  • 1
jims
  • 21
  • 1
  • 5

3 Answers3

3

Try this:

     SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
     format.setTimeZone(TimeZone.getTimeZone("UTC"));
     try {
         Date date1 = (Date) format.parse("4:15:20");
         Date date2 = (Date) format.parse("2:30:30");
         //time difference in milliseconds
         long timeDiff = date1.getTime() - date2.getTime(); 
         //new date object with time difference
         Date diffDate = new Date(timeDiff); 
         //formatted date string
         String timeDiffString = format.format(diffDate); 
         System.out.println("Time Diff = "+ timeDiffString );
     } catch (ParseException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     }

Above code has certain limitations. Other proper way could be to convert the long value of time difference manually in the string as below:

     long timeDiffSecs = timeDiff/1000;
     String timeDiffString = timeDiffSecs/3600+":"+
                             (timeDiffSecs%3600)/60+":"+
                             (timeDiffSecs%3600)%60;
     System.out.println("Time Diff = "+ timeDiffString);
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
0

The code you have will give you the number of milliseconds difference between the listed dates. It could be that the answer could be simply divide by 1000 to get the number of seconds.

PearsonArtPhoto
  • 38,970
  • 17
  • 111
  • 142
  • Sir,i have two times in HH:MM:SS format,now i want to substract the time1 from time2 and want to get result in HH:MM:SS format...can u please help? – jims Dec 25 '12 at 04:40
0

First Convert String date into simple Date formate

public String getconvertdate1(String date)
{
    DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    DateFormat outputFormat = new SimpleDateFormat("dd MMM yyyy");
    Date parsed = new Date();
    try
    {
        parsed = inputFormat.parse(date);
    }
    catch (ParseException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String outputText = outputFormat.format(parsed);
    return outputText;
}

//now can do anything with date.

 long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
 long days = diff / (24 * 60 * 60 * 1000);// you get day difference between

AND use simpledateFormate to configure HH:MM:SS

QuokMoon
  • 4,387
  • 4
  • 26
  • 50