问题
I have a DateTime field in my SQL database holding and when I try to show it in my JSP page and format it using "dd-MM-yyyy hh:mm:ss", it displays correctly only the date part. For example, for the date "2012-01-19 12:13:48" stored in the database it shows "19-01-2012 12:00:00". What may be the problem?
Code:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
sdf.format(rs.getDate("comment_date")); //rs -> ResultSet
回答1:
From the javadoc for java.sql.Date
:
To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
In order to preserve time information as well, you should be using java.sql.Timestamp
. In other words, change rs.getDate()
to rs.getTimestamp()
.
回答2:
An interesting date/time library you could have a look at is Joda Time. It solves many issues of the date/time implementations in the standard library.
来源:https://stackoverflow.com/questions/8951911/simpledateformat-not-showing-the-right-date-format