简体   繁体   English

如何将 node.js 日期转换为 SQL 服务器兼容日期时间?

[英]How to convert node.js date to SQL Server compatible datetime?

I have a Web Api using express and Tedious to store some data on Azure SQL database.我有一个 Web Api 使用ExpressTedious在 Azure SQL 数据库上存储一些数据。 With nvarchar types and int types it works well, but when I try to save DateTime value I get an error message:对于nvarchar类型和int类型,它运行良好,但是当我尝试保存DateTime值时,我收到一条错误消息:

Insert into Proxy (Ip, RequisitionDate) 
values ('1', '2016-05-18 3:32:21' )

Error:错误:

RequestError: Validation failed for parameter 'RequisitionDate'. RequestError:参数“RequisitionDate”的验证失败。 Invalid date.] message: 'Validation failed for parameter \'RequisitionDate\'.无效日期。] 消息:'参数 \'RequisitionDate\' 的验证失败。 Invalid date.', code: 'EPARAM' }无效日期。',代码:'EPARAM'}

Well, the interesting thing is that好吧,有趣的是

Insert into Proxy (Ip, RequisitionDate) 
values ('1', '2016-05-18 3:32:21')

is the query that i execute in node.js api:是我在 node.js api 中执行的查询:

var query = "Insert into Proxy (Ip,RequisitionDate) values ( '"+ ip + "', '"+ date + "' )";
console.log(query); // Insert into Proxy (Ip,RequisitionDate) values ( '1', '2016-05-18 3:32:21' )

request = new Request(query, function(err) {
    if (err) {
        console.log(err);}
    });

    request.addParameter('Ip', TYPES.NVarChar,'SQL Server Express 2014');
    request.addParameter('RequisitionDate', TYPES.DateTime , 'SQLEXPRESS2014');

    connection.execSql(request);
}

If I execute the query direct on the SqlManager Studio, it works ok.如果我直接在 SqlManager Studio 上执行查询,它工作正常。

It seems that you haven't set the correct datetime value in addParameter function.您似乎没有在addParameter函数中设置正确的datetime值。 According the API reference , the function is used as request.addParameter(name, type, value, [options]) .根据API 参考,该函数用作request.addParameter(name, type, value, [options])

Please try the following code:请尝试以下代码:

var query = "Insert into Proxy (Ip,RequisitionDate) values ( @ip , @date)";

request = new Request(query, function(err) {
    if (err) {
        console.log(err);}
    });

    request.addParameter('ip', TYPES.NVarChar,'<ip value>');
    request.addParameter('date', TYPES.DateTime , new Date());
// or the set the special date, refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
//  request.addParameter('RequisitionDate', TYPES.DateTime , new Date(2016,05,19,3,32,21))
    connection.execSql(request);
}

Any further concern, please feel free to let me know.任何进一步的问题,请随时告诉我。

A lot of people are having this issue.很多人都遇到这个问题。 This is how I normally solve it.这就是我通常解决它的方式。 Firstly, we need to understand that SQL tries to convert whatever date you send from your NodeJS code to UTC.首先,我们需要了解 SQL 会尝试将您从 NodeJS 代码发送的任何日期转换为 UTC。 So, how does SQL know how much difference should it add to make your date to UTC?那么,SQL 是如何知道应该添加多少差异才能使您的日期与 UTC 相符呢?

The answer is:答案是:

SHOW VARIABLES LIKE '%time_zone%';

if you write these command in sql query, it will show you system_time_zone and time_zone of your sql configuration.如果您在 sql 查询中编写这些命令,它将显示您的 sql 配置的 system_time_zone 和 time_zone。 In cases, where you simply send SQL datetime without mentioning the timezone from NodeJS, it will use this time_zone to convert your date to UTC.在某些情况下,如果您只是发送 SQL 日期时间而没有提及来自 NodeJS 的时区,它将使用此 time_zone 将您的日期转换为 UTC。 Now, what I recommend developers is to let SQL use UTC to store date and time and only convert the date to users timezone in frontend.现在,我建议开发人员让 SQL 使用 UTC 来存储日期和时间,并且只在前端将日期转换为用户时区。 What I personally do is, I send datetime to SQL along with the timezone.我个人所做的是,我将日期时间连同时区一起发送到 SQL。

moment.utc().format('YYYY-MM-DD HH:mm:ss Z')

Here Z is the timezone.这里 Z 是时区。 The date given by this code is此代码给出的日期是

2022-02-18 06:56:23 +00:00

Since, I used moment.utc(), the timezone is automatically set as +0:00.因为,我使用了 moment.utc(),时区自动设置为 +0:00。 If I send this format to SQL to store date, it will no longer try to convert the date to UTC format.如果我将这种格式发送到 SQL 来存储日期,它将不再尝试将日期转换为 UTC 格式。 But if I do但如果我这样做

moment.utc().format('YYYY-MM-DD HH:mm:ss');

SQL will convert this datetime using the system timezone offset, even if its already in UTC. SQL 将使用系统时区偏移量转换此日期时间,即使它已经在 UTC 中。 I recommend you not to use dialectOptions in your database connection module, since in future it will not be supported.我建议你不要在你的数据库连接模块中使用 dialectOptions,因为将来它不会被支持。 This is from my opinion a good way to store the date and time in sql. Now, as for showing the stored date to users.在我看来,这是在 sql 中存储日期和时间的好方法。现在,至于向用户显示存储的日期。 You can easily convert the UTC date stored in database to local syntax by using您可以使用以下方法轻松地将存储在数据库中的 UTC 日期转换为本地语法

moment(<database UTC datetime>).local().format('YYYY-MM-DD HH:mm:ss');

Good Luck, Have Fun Coding.祝你好运,玩得开心。

Sometimes you don't want to go to the trouble of creating named parameters, sometimes you just want to do some string templating. 有时您不想创建命名参数的麻烦,有时您只想进行一些字符串模板化。

At those times you can just convert your javascript date to an acceptable form using the built in toISOString function. 在那时,您可以使用内置的toISOString函数将javascript日期转换为可接受的形式。

So, in the above: 因此,在上面:

Insert into Proxy (Ip, RequisitionDate) 
values ('1', new Date().toISOString() );

Very quickly, you can use SQL server CONVERT function to convert your date string to be compatible with SQL server.很快,您可以使用 SQL server CONVERT 函数将日期字符串转换为与 SQL server 兼容。 Below is an example:下面是一个例子:

Insert into Proxy (Ip, RequisitionDate) values ('1', CONVERT(VARCHAR(10), '2020-8-24'))

For more info, you can check here: http://www-db.deis.unibo.it/courses/TW/DOCS/w3schools/sql/func_convert.asp.html有关更多信息,您可以在这里查看: http : //www-db.deis.unibo.it/courses/TW/DOCS/w3schools/sql/func_convert.asp.html

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

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