Store Java date and time in MySQL
Posted on 2010-04-06
How do I store a date and time in MySQL using java servlets?
First I create current date/time:
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
This is correct. I can output correct date and time:
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
gives correct date and time.
In prepared statement I use:
pstmt.setDate(5, new java.sql.Date(ticket.getCreationDate().getTime()));
When I check the table, it has only stored the date: 2010-04-06 00:00:00
The MySQL datatype is DATETIME.
I do not want to store it as a string, because I want to sort by date when retrieving the data.