Javascript nodejsmysql获取正确的时间戳格式

Javascript nodejsmysql获取正确的时间戳格式,javascript,node.js,Javascript,Node.js,我正在使用和从sql获取结果之后,我得到了不同的时间戳格式,如下所示: created_at: Sat Jul 16 2016 23:52:54 GMT+0430 (IRDT) 但它在mysql上是: 2016-07-16 23:52:54 我想得到的是,不是其他格式,我如何在mysql连接或sql命令上设置这种格式 var connection = mysql.createConnection({ host: 'localhost', user: 'root', p

我正在使用和从
sql
获取结果之后,我得到了不同的
时间戳
格式,如下所示:

created_at: Sat Jul 16 2016 23:52:54 GMT+0430 (IRDT)
但它在mysql上是:

2016-07-16 23:52:54
我想得到的是,不是其他格式,我如何在mysql连接或sql命令上设置这种格式

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'a',
    database: 'signal'
});

connection.query(command, function (err, rows) {
    if (err) throw err;
    console.log(rows);
});

我建议您处理行,而不是试图更改MySQL输出结果。这样,您的数据库将拥有有关创建日期的详细完整数据。而客户端(其他功能、系统、项目等)将把从DB检索到的值格式化为他们需要的任何格式。此外,您将通过系统为日期保留一致的返回结果。无论执行什么样的DB查询,您的软件总是希望返回相同的格式

以下是ES6中的一个示例,它还使用momente.js库来简化任何日期操作,强烈建议使用此库

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'a',
    database: 'signal'
});

function formatDate(date) {
  return moment(date).format('YYYY-MM-DD HH:mm:ss');
}

connection.query(command, (err, rows) => {
    if (err) {
      throw err;
    }

    rows = rows.map(row => ({
      ...row,
      created_date: formatDate(row.created_date)
    }));

    console.log(rows);
});
更新或在ES5中更新

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'a',
    database: 'signal'
});

function formatDate(date) {
  return moment(date).format('YYYY-MM-DD HH:mm:ss');
}

connection.query(command, function(err, rows) {
    if (err) {
      throw err;
    }

    rows = rows.map(function(row) {
      return Object.assign({}, row, { created_date: formatDate(row.created_date) });
    });

    console.log(rows);
});

这听起来难以置信,但在时间戳字符串上调用“.toString()”就足够了。这将提供人类可读的输出

只需将其添加到数据库连接配置中:

timezone: "America/Los_Angeles" // <-- change for whatever your TZ is

时区:“美国/洛杉矶”//谢谢,但是
…行,
?你能完成这一部分吗?谢谢,为什么我得到
[]
。问题是
参数数无效,这部分代码的参数数应为0..1
,{code>{},行,{create\u date:formatDate(row.create\u date)}
非常抱歉。我输入了
create\u date
而不是
created\u date
。我在答复中修正了这一点。另外,我这里有一个小提琴的例子来演示我的代码是如何工作的,谢谢。但是在JSFIDLE中我得到了这个错误:
ReferenceError:moment未定义
@mahdipishguy将moment.js添加到html页面(调用js文件的页面)