Date is not stored properly in db.
Hi all,
I have the follwing code:
publicstatic Date getTimeStamp()
{
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
return cal.getTime();
}
if I'll do system.out.println on the method I'll get (as of writing those lines):
Sat Sep 30 22:38:25 EDT 2006
when I write this date into mySql db the stored content is:
2006-09-30 00:00:00
* mind the 00:00:00
this is done despite the type of the column - which was set to: datetime.
can someone explain why the saved content is not: 2006-09-30 22:38:25 ?
and what should be done to save both date and time
Thank you
I do this:
public static Date getTimeStamp()
{
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
return cal.getTime();
}
and I also tried this:
public static Date getTimeStamp()
{
return new Date();
}
both store the same format, example: 2006-09-30 00:00:00
But how are you writing that date do the DB?
You should be doing something like this: Timestamp ts = new Timestamp(System.currentTimeMillis());
PreparedStatement ps = con.prepareStatement("insert into blah (name, timestamp) values (?, ?)"); // forgive the possibly incorrect SQL syntax
ps.setString(1, "George Francisco");
ps.setTimestamp(2, ts);
ps.executeUpdate();
If you're using Hibernate or some other ORM tool, you'll have to make sure all the pieces from the Java side through to the DB are properly handling this as a timestamp, not a java.sql.Date.
Note, also, that while java.util.Date includes hr, min, sec, ms, java.sql.Date does not. So what you get when you do new Date() depends on which Date you've imported.