• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to substract time and date  RSS feed

Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!