简体   繁体   English

如何从Java保存SQLServer 2014中的datetime列值

[英]How to save datetime column value in SQLServer 2014 from java

I tried using java.util.Date and java.sql.Date but in both the cases time part is not getting saved. 我尝试使用java.util.Date和java.sql.Date,但是在两种情况下都没有保存时​​间部分。

if date is 2015-11-16 17:53:49.6 如果日期是2015-11-16 17:53:49.6

it is saving it as 2015-11-16 00:00:00.000 in SQL Server. 它在SQL Server中将其另存为2015-11-16 00:00:00.000。

From the docs of java.sql.Date as it represents only date not the time( so the time value will be 00:00:00.000 which you are getting ). 从java.sql.Date的文档中 ,因为它仅表示日期而不是时间( 所以时间值将是00:00:00.000,即您正在获取 )。 So you have to add the time explicitly in your code or better use java.sql.Timestamp 因此,您必须在代码中显式添加时间,或者更好地使用java.sql.Timestamp

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. 为了符合SQL DATE的定义,必须通过将与实例相关联的特定时区中的小时,分​​钟,秒和毫秒设置为零,来“标准化” java.sql.Date实例包装的毫秒值。 。

Does using java.sql.Timestamp work ? 使用java.sql.Timestamp是否有效?

Check the data type of the SQL Server column too. 还要检查“ SQL Server”列的数据类型。

https://msdn.microsoft.com/en-us/library/ms378878(v=sql.110).aspx - This might help. https://msdn.microsoft.com/zh-cn/library/ms378878(v=sql.110).aspx-这可能会有所帮助。

You can use SQL GETDATE() function to get the current data and time.You can also fix it as default value while defining the table. 您可以使用SQL GETDATE()函数获取当前数据和时间。还可以在定义表时将其固定为默认值。 Example: 例:

CREATE TABLE Orders
(
OrderId int NOT NULL PRIMARY KEY,
ProductName varchar(50) NOT NULL,
OrderDate datetime NOT NULL DEFAULT GETDATE()
)

Moreover for insert statement you can use the query like this 此外,对于插入语句,您可以使用像这样的查询

INSERT INTO Orders (ColumnName) VALUES (GETDATE());

You can achive the same with the conversion like this 您可以通过这样的转换达到相同的效果

import java.text.SimpleDateFormat;

import java.util.Date;

class A3{
    public static void main(String[] args) throws Exception{

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-M-yyyy hh:mm:ss a");
        String dateWithSeconds = simpleDateFormat.format(date);
        System.out.println(dateWithSeconds);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM