Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

how to get difference of days between two Date

800425Aug 25 2007 — edited Aug 25 2007
hi everyone

what i am trying to do is get the difference of days between two dates.
first im creating a Calendar and then getting todays date and then i get another date from a database through jdbc....
i want to compare those two dates...if the difference is 4 days , i want to do something specific,....
im not being able to accomplish that....
is there is some kind of method in the API that does that....

this is my source code....
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Date;

public class DateThing {
    
    private Calendar c = Calendar.getInstance();
    private Date tD = new Date(c.get(Calendar.YEAR),c.get(Calendar.MONTH),c.get(Calendar.DAY_OF_MONTH));
    private Date dtc = null;
    
    
    /** Creates a new instance of DateThing */
    public DateThing(){
        dtc = getRetDate();
        
        if(tD.compareTo(dtc) > 0){
            int time = c.get(Calendar.DAY_OF_YEAR) - dtc.getDay();
            System.out.println(time);
        }
    }
    
    public Date getRetDate(){
        Date d = null;
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/dvd", "root", "password");
            
            String sql = "SELECT retdate " +
                    "FROM rental " +
                    "WHERE title_id = 245";
            
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            
            while(rs.next()){
                d = rs.getDate("retdate");
            }
            
            stmt.close();
            con.close();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        } catch (InstantiationException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }                        
        return d;
    }
    
    public static void main(String[] args){
        new DateThing();
    }
    
}
the date returned from the database is 2007-8-20 and todays date is 2007-8-25 so the integer time must have 5 in it....

please help me

thanks in advance
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 22 2007
Added on Aug 25 2007
12 comments
572 views