简体   繁体   English

如何使用Java Prepared语句在sqlserver的datetime字段中设置日期和时间

[英]How to Set date and time in datetime field in sqlserver using java prepared statement

I am receiving time in milliseconds and I would like to convert that into date and time format and store that value in datetime column in sqlserver . 我正在接收以毫秒为单位的时间,我想将其转换为日期和时间格式,并将该值存储在sqlserver的 datetime列中。

Following is the code which is working and converting milliseconds to date and time but it is unable to set the date and time value in database column. 以下是可以将毫秒转换为日期和时间的代码,但是无法在数据库列中设置日期和时间值。

    String datetime = 1488288835716
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(Long.parseLong(datetime));
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
    String datestring= formatter.format(calendar.getTime());
    UpdateStatement.setString(1,datestring)

You don't need to convert the given milliseconds into any textual representation. 您无需将给定的毫秒转换为任何文本表示形式。 In fact most databases store time / datetime values in milliseconds anyway. 实际上,大多数数据库无论如何都以毫秒为单位存储时间/日期时间值。

Instead, use java.sql.Timestamp like this: 而是使用java.sql.Timestamp如下所示:

long timeInMillis = 1488288835716;
Timestamp time = new Timestamp(timeInMillis);
updateStatement.setTimestamp(1, time);

Can you try this, to overcome possible issues with locale, culture and so on? 您可以尝试这样做,以解决区域设置,文化等方面的可能问题吗?

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

I am not proficient in Java, but this can be a problem with SQL Server, so I always put date strings in this format before writing to the database. 我不精通Java,但这可能是SQL Server的问题,因此在写入数据库之前,我总是以这种格式放置日期字符串。

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

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