我正在尝试从字符串示例 13:30(HH:MM) 创建日期对象(格式:HH:MM)。我想将 HH:MM 保存在 MySql 表中,但下面的代码在列中输入一些随机值(例如:'6828-00-00 00:00:00')。如何以 HH:MM 格式将日期值存储在 Mysql 中?
Date date = null;
String afternoon = "13" +":" +"30";
String time = afternoon;
try {
date = new SimpleDateFormat("HH:mm").parse(time);
}
catch (ParseException e) {
e.printStackTrace();
}
long d = date.getTime();
java.sql.Date sqlDate = new java.sql.Date(d);
String sql3 = "CREATE TABLE IF NOT EXISTS DateTime"+
"(UniqueBusID VARCHAR(255) not NULL, " +
" Timenings DATETIME DEFAULT NULL ,"+
" PRIMARY KEY ( UniqueBusID ))";
stmt.executeUpdate(sql3);
stmt.executeUpdate("INSERT INTO DateTime " + "VALUES ('Test3','"+sqlDate.getTime()+"')");
最佳答案
编辑
您必须使用java.sql.Timestamp
而不是java.sql.Date
。从 javadoc 来看,
"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."
所以只需替换该行
java.sql.Date sqlDate = new java.sql.Date(d);
与
java.sql.Timestamp sqlTime = new Timestamp(d);
<小时/>
你做得很好,除了你用来将String
解析为Date
的模式,即HH:mm
,这是错误的。
正确格式:H:mm
(H
: 0-23; h
:1-12)
try {
date = new SimpleDateFormat("H:mm").parse(time);
}
这是 Date and Time Patterns
的引用
关于java - 如何将日期对象存储到MySql中的HH :MM format?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21923601/