Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Calculating the Time Difference

 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Martijn Verburg
author
Bartender
Posts: 3275
5
Eclipse IDE Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic