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

[823 byte] By [xianwinwina] at [2007-10-3 6:15:29]
# 1
xian,I've allways just gotten a new Date() to get the current datetime... and I've never had a problem storing them in a mysql database... So try Date instead of using the Calender.Hope that helps. Keith.
corlettka at 2007-7-15 0:59:48 > top of Java-index,Java Essentials,Java Programming...
# 2
return new Date() - still, the stored content is without the time
xianwinwina at 2007-7-15 0:59:48 > top of Java-index,Java Essentials,Java Programming...
# 3
How is your Java code storing the date? My guess is you're using a java.sql.Date, rather than java.sql.Timestamp.
jverda at 2007-7-15 0:59:48 > top of Java-index,Java Essentials,Java Programming...
# 4

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

xianwinwina at 2007-7-15 0:59:48 > top of Java-index,Java Essentials,Java Programming...
# 5

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.

jverda at 2007-7-15 0:59:48 > top of Java-index,Java Essentials,Java Programming...
# 6
jverd, thanks I got it!I looked at the code (I'm using iBatis) and apprently my xml looked like this:insert.... values.... #activation:DATE#I changed it to: #activation:DATETIME#this works! thanks again.
xianwinwina at 2007-7-15 0:59:48 > top of Java-index,Java Essentials,Java Programming...