【问题标题】:Date in response JSON is different than in database响应 JSON 中的日期与数据库中的日期不同
【发布时间】:2015-05-18 15:33:12
【问题描述】:

我有sails.js 应用程序。 当我将记录添加到我的 MySQL 数据库时,有一个字段 createdAt - 类型 dateTime。 在 MySql 控制台中 createdAt 值看起来像 Wed Mar 25 2015 00:00:00 GMT+0100 当我尝试使用sails.js 控制器将这些数据作为JSON 获取时,我得到了 2015-03-24T23:00:00.000Z - 1 小时后? 我的系统时区是 GMT +1。 如何在 db 和 JSON 响应中获得相同的时间?

   'list': function (req, res, next) {

 Tests.find().exec(function (err, tests) {
   if (err) res.json({ error: 'DB error' }, 500);
   if (tests) {
     _.each(tests, function (data) {
       console.log("Date: " + JSON.stringify(data.createdAt)+"   "+data.createdAt);
     })
     res.status(200).json(tests);
   }
 });

控制台输出为:

 Date: "2015-03-10T14:28:51.000Z"   Tue Mar 10 2015 15:28:51 GMT+0100
Date: "2015-03-16T10:25:34.000Z"   Mon Mar 16 2015 11:25:34 GMT+0100
Date: "2015-03-16T11:27:23.000Z"   Mon Mar 16 2015 12:27:23 GMT+0100
Date: "2015-03-16T11:33:39.000Z"   Mon Mar 16 2015 12:33:39 GMT+0100
Date: "2015-03-16T11:34:41.000Z"   Mon Mar 16 2015 12:34:41 GMT+0100
Date: "2015-03-16T12:13:21.000Z"   Mon Mar 16 2015 13:13:21 GMT+0100
Date: "2015-03-16T13:54:03.000Z"   Mon Mar 16 2015 14:54:03 GMT+0100

这一切都是在转换为 JSON 时发生的 - 仍然不知道如何修复它。

【问题讨论】:

  • 听起来像是两次应用时区偏移。您可能想通过暂时进入不同的时区来检查,例如为美国。接下来,发布代码 - 我们不知道问题是您从数据库中获取数据时出现的问题,还是作为响应的一部分被序列化时出现的问题。
  • 数据看起来不错,我认为问题出在不同格式的打印中
  • [stackoverflow 问题 1486476][1] [1] 的可能重复项:stackoverflow.com/questions/1486476/…
  • 它是相似的,但解决方案在这里很合适。我的服务器和客户端在同一个时区,当我从查询发送结果集作为 json 响应时,我不想遍历结果集来转换所有日期文件。

标签: json sails.js


【解决方案1】:

JSON.stringify(data.createdAt) 等于data.createdAt.toJSON() 并且等于data.createdAt.toISOString()

data.createdAt 等于 data.createdAt.toString()

时间值相等; toString() 根据您的时区返回它,而toISOString() 在 GMT 时返回。

要从JSON字符串中获取日期,使用转换函数作为JSON.parse()的第二个参数,您可以使用正则表达式rx = /([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})\.([0-9]{3})Z/检查日期ISO格式,然后将其转换为日期d = new Date(str)

【讨论】:

  • new Date('2015-03-16T21:10:30.000Z') 或 new Date(1426540230000) 创建UTC日期2015-03-16 21:10:30; new Date(2015,2,16,21,10,30,0) 创建您的本地日期 2015-03-16 21:10:30 GMT+-您的时区; new Date() 创建您当前的本地日期
【解决方案2】:

你的 Mysql 数据库中 createdAt 的类型是什么?是日期吗?如果是,请尝试将其设置为 varchar。如果您需要对其进行操作或格式化,您可以使用 moment js。

【讨论】:

    猜你喜欢
    • 2022-09-30
    • 2016-12-19
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 2011-03-26
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多