Issue converting from java.util.Date to java.sql.Timestamp
I'm trying to put a user provided date into an SQL database, and I have the following lines to process the string and convert it to a java.sql.Timestamp object.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm");
java.util.Date badDate = formatter.parse(request.getParameter("datetime"));
Timestamp date = new Timestamp(badDate.getTime开发者_运维百科());
The issue is, badDate is the correct date that the user input, but date always gets set to the wrong month and day, usually January 2, and the correct time and year. I had the same problem when I tried to convert to a java.sql.Date object, but then the time was set to midnight as well. I couldn't find anyone with a similar problem after some searching, maybe someone here has seen something like this?
The date format is wrong, it should be yyyy-MM-dd'T'HH:mm
.
Please refer this document for details about date format.
m
stands for Minutes
M
for Months
h
for hours in am/pm (1-12)
H
for hours in 24 hour clock
It will be better if you can give a sample of the date value you are trying to parse.
You want "yyyy-MM-dd'T'hh:mm"
(note capitalized MM). Otherwise your month is wrong in the format string.
精彩评论