NodeJS 转换 MYSQL 日期

NodeJS convert MYSQL Date

我对 nodejs 作为输出提供的时间格式有点吃力。

我执行 MYSQL 查询并返回日期时间(f.e 2020-01-08 20:20:25 是我数据库中的一个条目) 当我从查询中得到结果时,输出看起来像 Wed Jan 08 2020 20:20:25 GMT+0100 (GMT+01:00)

我找不到从我的数据库中"convert"恢复格式的方法,你对此有什么解决方案吗?

非常感谢。

当您创建实例时,只需添加使用日期作为字符串的配置

mysql.createConnection({
  dateStrings: true
});

我建议使用名为 Moment.js 的第三方模块。您可以使用 npm install moment --save 来安装模块。它有助于使用自定义格式进行日期转换。

下面是我的代码:

const moment = require('moment'); // Importing the Moment.js module

const date = moment(
    "Wed Jan 08 2020 20:20:25 GMT+0100 (GMT+01:00)",
    "ddd MMM DD YYYY HH:mm:ss"
); // This is your query from MySQL

let mydate = date.format("YYYY-MM-DD HH:mm:ss"); // Using moment.format() with the given format, it converts the date

console.log(mydate) // Finally outputting the date to the console

以下代码输出:2020-01-08 20:20:25