从 java.util.Date 转换为 java.sql.Timestamp 的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5864751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Issue converting from java.util.Date to java.sql.Timestamp
提问by pickypg
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.
我正在尝试将用户提供的日期放入 SQL 数据库,并且我有以下几行来处理字符串并将其转换为 java.sql.Timestamp 对象。
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?
问题是,badDate 是用户输入的正确日期,但日期总是设置为错误的月份和日期,通常是 1 月 2 日,以及正确的时间和年份。当我尝试转换为 java.sql.Date 对象时遇到了同样的问题,但随后时间也设置为午夜。经过一番搜索,我找不到任何有类似问题的人,也许这里有人见过这样的事情?
回答by Arun P Johny
The date format is wrong, it should be yyyy-MM-dd'T'HH:mm
.
日期格式不对,应该是yyyy-MM-dd'T'HH:mm
。
Please refer this documentfor 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
m
代表 Minutes M
for Monthsh
表示 am/pm (1-12)H
中的小时数,表示 24 小时制中的小时数
It will be better if you can give a sample of the date value you are trying to parse.
如果您可以提供您尝试解析的日期值的示例,那就更好了。
回答by pickypg
You want "yyyy-MM-dd'T'hh:mm"
(note capitalized MM). Otherwise your month is wrong in the format string.
你想要"yyyy-MM-dd'T'hh:mm"
(注意大写的MM)。否则你的月份在格式字符串中是错误的。