Many a times we need to insert the date of transaction in the database, but the problem is that the PreparedStatement Implementations have a setDate() method which takes java.sql.Date as an argument and same is the case with the ResultSet which is returned from the database as java.sql.Date is an equivalent to Date datatype in the DB.
But in java we can get current date from a new Object of java.util.Date, so here is how to convert it into java.sql.Date
java.util.Date today = new java.util.Date();
java.sql.Date date = new java.sql.Date(today .getTime());
java.sql.Date only saves the date though and not other attributes like day, time, timezone etc.
If the field in the Database is defined as DATETIME then we can use java.sql.Timestamp instead.
java.sql.Timestamp ts = new java.sql.Timestamp(today .getTime());
here is the result
System.out.println(today); ---> Fri May 01 17:54:26 IST 2009 (util.Date)
System.out.println(date); ---> 2009-05-01 (sql.Date)
System.out.println(ts); ---> 2009-05-01 17:54:26.199 (sql.Timestamp)
Timestamp doesn't hold timezone and day attributes.
Thats it for now folks.
LazyCoder
Signing off for now...
Friday, May 1, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment