Java字符串到日期转换为null,写入SQL数据库问题
我有一个 Date
,它已转换为 String
以传递到 Java Socket
服务器。此值的示例是06:19:18p.m。 2011 年 1 月 13 日
。
在 Socket
服务器中,我尝试将其转换回 Date
值,然后再将其写入 SQL 数据库表,但转换后的值为 NULL
代码>.我还尝试将值作为原始 String
写入 SQL 数据库,但除非其中没有冒号、句号或正斜杠字符,否则它不会写入。
有什么办法可以解决这个问题吗?很抱歉,我无法查看或发布堆栈跟踪,因为我没有运行 Jar 文件的服务器的管理员访问权限。
我转换 String
的代码是:
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ssa dd/MM/yyyy");
try {
date = sdf.parse(timestamp);
}
catch (ParseException e) {
e.printStackTrace();
}
I have a Date
that has been converted to a String
to be passed to a Java Socket
server. An example of this value is 06:19:18p.m. 13/01/2011
.
Within the Socket
server I'm trying to convert it back to a Date
value before writing it to a SQL Database table, but the converted value is NULL
. I have also tried writing the value to the SQL database as the original String
, but it doesn't write unless there are no colon, full stop, or forward-slash characters in it.
Is there any way I can get around this? I'm sorry that I can't view or post the stack trace, as I don't have admin access to the server I'm running my Jar file on.
My code to convert the String
is:
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ssa dd/MM/yyyy");
try {
date = sdf.parse(timestamp);
}
catch (ParseException e) {
e.printStackTrace();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不知道为什么你不能正确解析,但你对此的想法都是错误的。您应该将列设置为 TIMESTAMP 或 DATE 类型,而不是将 String 保存在数据库中。然后您可以使用 JDBC 中的 getDate() 来获取日期对象。
I am not sure why you can't parse correctly but you are thinking all wrong about this. Instead of saving String in the database you should make the column of type TIMESTAMP or DATE. Then you can use getDate() from the JDBC to just get the date object.
SimpleDateFormat 模式中的“a”只能解析“AM”或“PM”,但不能解析“pm”。只要改变它,你的解析就会成功。
The "a" in your SimpleDateFormat pattern can only parse "AM" or "PM", but not "p.m.". Just change that and your parsing will be successful.
这可能只是一个拼写错误,但您的“06:19:18p.m. 13/012011”示例与您的简单日期格式不匹配,因为它期望您的日期中有两个斜杠。
找到一种方法来获取堆栈跟踪或在其他地方单独在数据上尝试此代码将非常有用,这样您就可以确保您得到的不仅仅是坏数据。
This might just be a typo but your example of "06:19:18p.m. 13/012011" does not match your simple date format because it expecting two slashes in your date.
It would be very useful to find a way to get the stack track or try this code out on the data separately elsewhere so that you can make sure you aren't just getting bad data.