In a java application what would a good compromise in terms of extracing and inputting date information with a MySQL database using a mix of datetimes and timestamps?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
In Java side, the date is usually represented by the (poorly designed, but that aside)
java.util.Date
. It is basically backed by the Epoch time in flavor of along
, also known as a timestamp. It contains information about both the date and time parts. In Java, the precision is in milliseconds.In SQL side, there are several standard date and time types,
DATE
,TIME
andTIMESTAMP
(at some DB's also calledDATETIME
), which are represented in JDBC asjava.sql.Date
,java.sql.Time
andjava.sql.Timestamp
, all subclasses ofjava.util.Date
. The precision is DB dependent, often in milliseconds like Java, but it can also be in seconds.In contrary to
java.util.Date
, thejava.sql.Date
contains only information about the date part (year, month, day). TheTime
contains only information about the time part (hours, minutes, seconds) and theTimestamp
contains information about the both parts, like asjava.util.Date
does.The normal practice to store a timestamp in the DB (thus,
java.util.Date
in Java side andjava.sql.Timestamp
in JDBC side) is to usePreparedStatement#setTimestamp()
.The normal practice to obtain a timestamp from the DB is to use
ResultSet#getTimestamp()
.The MySQL documentation has information on mapping MySQL types to Java types. In general, for MySQL datetime and timestamps you should use
java.sql.Timestamp
. A few resources include:http://dev.mysql.com/doc/refman/5.1/en/datetime.html
http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion
How to store Java Date to Mysql datetime...?
http://www.velocityreviews.com/forums/t599436-the-best-practice-to-deal-with-datetime-in-mysql-using-jdbc.html
EDIT:
As others have indicated, the suggestion of using strings may lead to issues.
BalusC gave a good description about the problem but it lacks a good end to end code that users can pick and test it for themselves.
Best practice is to always store date-time in UTC timezone in DB. Sql timestamp type does not have timezone info.
When writing datetime value to sql db
When reading the value back from DB into java,
Then, change it to your desired timezone. Here I am changing it to Toronto timezone.