*
The moose likes Beginning Java and the fly likes Calculating the Time Difference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Calculating the Time Difference" Watch "Calculating the Time Difference" New topic
Author

Calculating the Time Difference

Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Hi All,

can anybody give an idea that how to calculate the time difference ? example : substract 04:28:23(HH:MM:SS) from 14:27:48

note:i searched in google but i am not getting that

Thanks and Regards,
seetharaman.v
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3426
    
  12
Convert the two times to a number of seconds and then subtract one from the other. You could then convert the result back to hours/minutes/seconds if you need to.


Joanne
Martijn Verburg
author
Bartender

Joined: Jun 24, 2003
Posts: 3274
    
    5

Copied from the Sun forum (I thought this was a good post on the topic that I found awhile back)

--------------

For manipulating time dates use the Calendar class. This has an 'add' and a roll method that will calculate the correct roll over values, should the time roll over to the next day etc. It also does clever things like sort out leap years etc.

so to subtract your 12hr, 30 mins:

Date myDate = new Date(); // This is the date from which you wish to subtract.

Calendar cal = Calendar.getInstance();
cal.setTime(myDate);

// Note you 'add' a negative number. i.e. subtract
cal.add(Calendar.HOUR_OF_DAY, -12 );
cal.add(Calendar.MINUTE, -30 );

Date newTime = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SS");
System.out.println("new time=" + sdf.format(newTime));

The Date class is the holder of the absolute time, the Calendar is the manipulator of those times and the SimpleDateFormat will format your Date class into an acceptable output format.

Hope this helps.


Cheers, Martijn - Blog,
Twitter, PCGen, Ikasan, My The Well-Grounded Java Developer book!,
My start-up.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Thanks all
 
wood burning stoves
 
subject: Calculating the Time Difference
 
Similar Threads
Clarification
Using System.currentTimeMillis() method
difference between import and import...
script time out & page time out in JSP
latency and response