Re: the best practice to deal with datetime in mysql using jdbc?
lightning wrote:
I found that standard jdbc [sic] api [sic] does not have a very convenient way to
deal with datetime.
Maybe not, but it does have very convenient ways to deal with TIMESTAMP.
So I use it in this way:
DateFormat df =
DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG,
Locale.CHINA);
DateFormat dfp =
DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM,
Locale.CHINA);
String output=df.format(dfp.parse(rs.getString("time")));
Is this the best practice ?
No. It's pretty much worst practice.
Logically, a "datetime", really a SQL TIMESTAMP as there is no such thing as a
"datetime" in Java or SQL, is not formatted, just an abstract representation
of a moment.
Normally you wouldn't store such a value as a CHAR, VARCHAR or other text
variant. You'd store it as a TIMESTAMP. So ResultSet.getString() is the
wrong method to use. The right method is getTimestamp().
Likewise you have getDate() and getTime() for SQL DATE and TIME values,
respectively.
The Java types for TIMESTAMP, DATE and TIME are java.sql.Timestamp,
java.sql.Date and java.sql.Time, respectively. All three are direct
subclasses of java.util.Date. Read the docs carefully; there are significant
caveats to these classes.
--
Lew