java sql 日期时间 [英] java sql date time
问题描述
当我将 SQL DateTime
插入数据库时,我得到 2007-02-07 12:00:00.00
When I insert a SQL DateTime
to the database I get 2007-02-07 12:00:00.00
但我制作了这样的 Date
对象:2007-02-07 17:29:46.00
But I made the Date
object like this : 2007-02-07 17:29:46.00
如何获取数据库中秒的值.它总是把它改回 12:00:00.00
How to get the value of the seconds in the database. It always changes it back to 12:00:00.00
date.setYear(Integer.valueOf(parsedDate[2].replaceAll(" ", "")) - 1900);
date.setMonth(Integer.valueOf(parsedDate[0].replaceAll(" ", "")));
date.setDate(Integer.valueOf(parsedDate[1].replaceAll(" ", "")));
...
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
我应该使用任何格式化程序吗?
Should I use any formatters?
推荐答案
java.sql.Date
表示日期,而不是日期和时间.来自文档:
java.sql.Date
represents a date, not a date and time. From the docs:
为了符合 SQL DATE 的定义,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.
如果你想存储日期和时间,你应该寻找另一种类型 - 例如java.sql.Timestamp
.这并不是建议您使用 TIMESTAMP 列类型 - 正如 paulsm4 在评论中所说,这是另一回事.但是,据我所知,JDBC只支持:
If you want to store a date and time, you should look for another type - e.g. java.sql.Timestamp
. That's not suggesting you use a TIMESTAMP column type - as paulsm4 says in the comments, that's a different thing. However, as far as I can see, JDBC only supports:
Date
(不,你也想要时间)时间
(不,你也想要约会)Timestamp
(包括日期和时间,但您不想要 TIMESTAMP SQL 语义)
Date
(no, you want a time too)Time
(no, you want a date too)Timestamp
(includes a date and time, but you don't want TIMESTAMP SQL semantics)
我会期望使用带有 DATETIME 列的 Java Timestamp
类型来工作,尽管没有 Timestamp
提供的精度级别.
I would expect using the Java Timestamp
type with a DATETIME column to work, although without the level of precision that Timestamp
provides.
经过更多研究,看起来您可能想要使用 java.sql.Time
类型,但具有特殊的驱动程序参数 - 至少如果您正在使用 Microsoft 驱动程序.有关详细信息,请参阅有关配置 JDBC 的这些文档.
After a bit more research, it looks like you may want to use the java.sql.Time
type, but with special driver parameters - at least if you're using the Microsoft driver. See these docs on configuring JDBC for more information.
这篇关于java sql 日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!