Question:
I have a ResultSet created using JDBC and it contains some date
fields. Now I want to subtract one date from the other. How
do I do this?
Answer:
Date arithmetic in Java is performed by instances of the Calendar
class. The Date class, and subclasses thereof, are place holders for date
and time information, but do not support arithmetic operations. To
add or subtract dates you need to set the time, represented by a
Calendar instance, to that contained in a Date object. You can do this
with Calendar.setTime(Date), which accepts a Date parameter.
The java.sql.Date and java.sql.Timestamp classes are both subclasses
of java.util.Date, so they may be used to set the Calendar's
time value. Additions and subtractions are done one field at a time with
add(int field, int amount), and negative amounts are used to
subtract time. The following example simulates getting a date from a
database and subtracts a day from it.
import java.util.*;
public final class DateToCalendar {
public static final Date queryDate() {
return new Date();
}
public static final void main(String[] args) {
Date today, yesterday;
Calendar calendar;
today = queryDate();
calendar = Calendar.getInstance();
calendar.setTime(today);
calendar.add(Calendar.DATE, -1);
yesterday = calendar.getTime();
System.out.println("Today : " + today.toString());
System.out.println("Yesterday: " + yesterday.toString());
}
}