jQuery in Action, 3rd edition
The moose likes JSP and the fly likes Subtracting Time (Date) in JSP Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Java » JSP
Bookmark "Subtracting Time (Date) in JSP" Watch "Subtracting Time (Date) in JSP" New topic

Subtracting Time (Date) in JSP

Philip Cheshire

Joined: May 06, 2003
Posts: 6
I need to calculate the difference in two times. I've created two calendars, one with the current time and one set to a specific time. I need to subtract them and calculate the difference in Months, days, hours, minutes, and seconds.
I've been searching the web for a week now and I can't seem to find anything.
Someone help please!!!

BookTrading.net, coming fall '03!

Joined: Oct 08, 2002
Posts: 6
could you simple convert to millisecs the date and make a simple operation like
long dif = date1.getTime() - date2.getTime()
dif is the difference on milliseconds
Philip Cheshire

Joined: May 06, 2003
Posts: 6
This is the error I get when I try that:
/tomcat/work/Standalone/#########_jsp.java:433: operator - cannot be applied to java.util.Date,java.util.Date
long dif = AuctionCalendar.getTime() - calendar.getTime();
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63211

That's because the getTime() method of Calendar returns a Date, whose getTime() method returns the long value in msecs.
So in order to convert a calendar to its msec equivalent you need to use something along the lines of:

P.S. For future posts: this is a general Java question and should have been posted in the Java (Beginner) forum; just because you are trying to do this in a JSP doesn't make it a JSP question.

[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Philip Cheshire

Joined: May 06, 2003
Posts: 6
Thanks Hernando, after a little bit of tweaking to my application, it works great!!
Mucho Gracias
I agree. Here's the link: http://aspose.com/file-tools
subject: Subtracting Time (Date) in JSP
It's not a secret anymore!