File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes how to substract time and date Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how to substract time and date" Watch "how to substract time and date" New topic

how to substract time and date

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
How can I substract time and date so as to get output in int.
The example is metioned below. I need output in "int" in format mentioned below.
for example
int time=(20:30:00-02:45:00)

int date=(2001-12-7)-(2000-4-6)
Brett Spell
Ranch Hand

Joined: Feb 24, 2001
Posts: 107
If I understand correctly, you're wanting to find the difference between two points in time (e.g., the difference between two times in hours, minutes, and seconds or difference between two dates in years, months, and days).
Hopefully you're already aware that a point in time (a date, a time, or a combination of the two) is represented by an instance of the java.util.Date class. In addition, the java.util.Calendar class and its subclasses such as GregorianCalendar allow you to parse, format, and manipulate these values. I won't go into how to use Date or Calendar here, because I'm sure that those are covered in other posts. However, assuming that you have your two points in time stored in instances of Date called "date1" and "date2", you can use the following code to display the difference between them:
// Get the amount of time between the two dates
long msecs = date1.getTime() - date2.getTime();
// Create a GregorianCalendar and set its time zone to GMT
GregorianCalendar delta = new GregorianCalendar(
new SimpleTimeZone(0, ""));
// Set the calendar's time to the difference between the two
delta.setTime(new Date(Math.abs(msecs)));
// The "base" year is 1970, so subtract that number
System.out.println("Years: " +(delta.get(Calendar.YEAR) - 1970));
System.out.println("Months: " + delta.get(Calendar.MONTH));
// The "base" date is 1, so subtract that number
System.out.println("Days: " + (delta.get(Calendar.DATE) - 1));
System.out.println("Hours: " + delta.get(Calendar.HOUR));
System.out.println("Minutes: " + delta.get(Calendar.MINUTE));
System.out.println("Seconds: " + delta.get(Calendar.SECOND));

Brett Spell,
Author, Professional Java Programming
[This message has been edited by Brett Spell (edited February 24, 2001).]
I agree. Here's the link:
subject: how to substract time and date
It's not a secret anymore!