JavaScript 函数
Date.now()
返回毫秒级的纪元时间。 Mysql 驱动程序,
knex
用于发送查询的操作,期望您将 ISO8601 字符串或
Date()
对象传递给
DATETIME
列。
日期对象将转换为 'YYYY-mm-dd HH:ii:ss' 格式的字符串。
https://github.com/mysqljs/mysql
所以,不要使用
Date.now()
,而是使用
new Date()
或
new Date().toISOString()
编辑:
只是检查mysql是否真的接受
.toISOString()
输出,因为我在文档
https://dev.mysql.com/doc/refman/5.7/en/date-and-time-type-overview.html中找不到相关说明。
MariaDB [(none)]> select CAST('2017-01-30T16:49:19.278Z' AS DATETIME);
+
| CAST('2017-01-30T16:49:19.278Z' AS DATETIME) |
+
| 2017-01-30 16:49:19 |
+
1 row in set, 1 warning (0.00 sec)
看起来是真的。耶!一切都好。
编辑2:实际上,仅使用.toISOString()
会导致某些情况下出现警告和错误,因此插入UTC DATETIME列时应该使用.toISOString().replace('Z','').replace('T', ' ')
或任何其他首选方法将UTC datetime对象转换为格式yyyy-MM-dd HH:mm:ss
。
另外,如果您正在使用TIMESTAMP列类型,并且想要将UTC时间插入数据库,则重要的是还将数据库会话设置为UTC。否则,javascript时间戳将被解释为本地数据库时间,并在存储之前从其转换为UTC。
CREATE TABLE test (descr TEXT, dt DATETIME, ts TIMESTAMP);
SET time_zone = '+8:00';
INSERT INTO test (descr, dt, ts) VALUES
('session tz +08:00 insert local times', '2020-01-01T00:00:00', '2020-01-01T00:00:00');
SET time_zone = '+0:00';
INSERT INTO test (descr, dt, ts) VALUES
('session tz +00:00 insert local times', '2020-01-01 00:00:00', '2020-01-01 00:00:00');
SET time_zone = '+02:00';
select 'server local time:', now();
select * from test;
SET time_zone = '+08:00';
select 'server local time:', now();
select * from test;
---
**Query #1**
SET time_zone = '+02:00';
There are no results to be displayed.
---
**Query #2**
select 'server local time:', now();
| server local time: | now() |
| ------------------ | ------------------- |
| server local time: | 2020-05-10 16:38:26 |
---
**Query #3**
select * from test;
| descr | dt | ts |
| ------------------------------------ | ------------------- | ------------------- |
| session tz +08:00 insert local times | 2020-01-01 00:00:00 | 2019-12-31 18:00:00 |
| session tz +00:00 insert local times | 2020-01-01 00:00:00 | 2020-01-01 02:00:00 |
---
**Query #4**
SET time_zone = '+08:00';
There are no results to be displayed.
---
**Query #5**
select 'server local time:', now();
| server local time: | now() |
| ------------------ | ------------------- |
| server local time: | 2020-05-10 22:38:26 |
---
**Query #6**
select * from test;
| descr | dt | ts |
| ------------------------------------ | ------------------- | ------------------- |
| session tz +08:00 insert local times | 2020-01-01 00:00:00 | 2020-01-01 00:00:00 |
| session tz +00:00 insert local times | 2020-01-01 00:00:00 | 2020-01-01 08:00:00 |
---
在DB Fiddle上查看
展示了存储和读取时间戳实际上总是作为本地时间处理,而DATETIME与数据库会话的时区设置无关。
通过快速测试,我甚至无法使yyyy-MM-dd HH:mm:ss+zz:zz
类型的时间戳/日期时间在mysql 8上工作。
Date.now()
部分,我无法确定,因为我不了解X.js
方法。您正在使用的其他方法/脚本需要传递为YYYY-MM-DD 00:00:00
以用于DATETIME
。 - Funk Forty Ninerstrtotime()
或MySQL的DATE_FORMAT()
来进行查询。 - Funk Forty Niner