How do I create a java.sql.Date object?

Joe Sam Shirah

java.sql.Date descends from java.util.Date, but uses only the year, month and day values. There are two methods to create a Date object. The first uses a Calendar object, setting the year, month and day portions to the desired values. The hour, minute, second and millisecond values must be set to zero. At that point, Calendar.getTime().getTime() is invoked to get the java.util.Date milliseconds. That value is then passed to a java.sql.Date constructor:


    Calendar cal = Calendar.getInstance();
    
    // set Date portion to January 1, 1970
    cal.set( cal.YEAR, 1970 );
    cal.set( cal.MONTH, cal.JANUARY );
    cal.set( cal.DATE, 1 );
    
    cal.set( cal.HOUR_OF_DAY, 0 );
    cal.set( cal.MINUTE, 0 );
    cal.set( cal.SECOND, 0 );
    cal.set( cal.MILLISECOND, 0 );
    
    java.sql.Date jsqlD = 
       new java.sql.Date( cal.getTime().getTime() );
The second method is java.sql.Date's valueOf method. valueOf() accepts a String, which must be the date in JDBC time escape format - "yyyy-mm-dd". For example,

    java.sql.Date jsqlD = java.sql.Date.valueOf( "2010-01-31" );
creates a Date object representing January 31, 2010. To use this method with a Calendar object, use:

    java.sql.Date jsqlD = java.sql.Date.valueOf( 
            cal.get(cal.YEAR) + ":" + 
            cal.get(cal.MONTH) + ":" + 
            cal.get(cal.DATE) );
which produces a Date object with the same value as the first example.
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact