首页 > 解决方案 > NodeJS 转换 MYSQL 日期

问题描述

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

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

我找不到将其从我的数据库“转换”回格式的方法,您对此有什么解决方案吗?

非常感谢。

标签: mysqlnode.jsdate-format

解决方案


我建议使用名为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


推荐阅读