【问题标题】:Why is my date from mysql decrementing by one day in javascript?为什么我的 mysql 日期在 javascript 中减少了一天?
【发布时间】:2017-04-08 01:53:38
【问题描述】:

我有一个存储在 mysql 数据库中的待办事项列表,存储的列是 todoTitle 和 todoDate,当我将 todoDate 打印到屏幕上时,如您在下面的代码中所见,它将显示递减一天的日期,例如,如果数据库中的日期显示 2016-12-20 它将在我的网站上显示 2016-12-19。

如果您想知道为什么将 todoDate 变成字符串然后再变成子字符串,那是因为如果我不这样做,它会像这样打印出来:2016-12-19T23:00:00.000Z

var xhr = new XMLHttpRequest();                 // Create XMLHttpRequest object

xhr.onload = function() {// When readystate changes
// The following conditional check will not work locally - only on a server
if(xhr.status === 200) {                      // If server status was ok
responseObject = JSON.parse(xhr.responseText);

// BUILD UP STRING WITH NEW CONTENT (could also use DOM manipulation)
var newContent =
    "<tr>" +
    "<td>" + "Activity" + "</td>" +
    "<td>" + "Due Date" + "</td>" +
    "</tr>";
for (var i = 0; i < responseObject.length; i++) { // Loop through object
    newContent += "<tr>";
    newContent += "<td>" + responseObject[i].todoTitle + "</td>";
    newContent += "<td>" + responseObject[i].todoDate.toString().substring(0,10) + "</td>";
    newContent += "</tr>";
}

// Update the page with the new content
document.getElementById('content').innerHTML = newContent;

}
};

//xhr.open('GET', 'data/data.json', true);  // Dummy JSON Data
xhr.open('GET', 'http://127.0.0.1:8000/todo/', true);        // Prepare the request
xhr.send(null);                                 // Send the request

【问题讨论】:

  • 时区申请?你看到 23:00 和 Z 的完整时间戳了吗?
  • 关于.toStrong().substring(),是否无法格式化日期服务器端?这将解决 ISO 日期字符串格式。另外,您能否为我提供responseObject[i].todoDate 的值和类型?
  • @VaoTsun 它曾经在我的 mysql 数据库中属于 TIMESTAMP 数据类型,但我将其列更改为 DATE 数据类型,并且它确实以 YYYY-MM-DD 格式保存在我的数据库中,即我想要什么,但是当我在网站上显示它时,它会显示完整的时间戳
  • @tbirrell 不确定您对这两个问题的要求是什么,因为我是初学者...=(
  • 您似乎使用 datetime 列类型(但因此“Z”令人困惑,您是否在服务器上进行了一些额外的处理?)无论如何 88.8% 是时区问题,请阅读:stackoverflow.com/questions/19843203/…

标签: javascript html mysql node.js date


【解决方案1】:

Z 表示“零小时偏移”,也称为“祖鲁时间”(UTC)。当您从数据库中查询日期时,有两种可能的情况是日期发生变化,在数据库层或在应用程序层,将其调整为您所在的时区。

因此,例如,如果数据库设置在您获得实际数据时自动将时间保存为 UTC,它将转换为您当前的时区。但是从您的示例 2016-12-20 转换为 2016-12-19T23:00:00.000Z 然后我假设您的数据库设置将其保存在某个时区,然后将其转换为 UTC。

要修复它,请尝试调整您的应用程序逻辑或数据库设置,对我而言,我宁愿在应用程序级别进行,并在数据库中维护日期以保存为 UTC。

试试这个看看有什么不同,可以给你解决问题的提示:

var currentDate = new Date();
var isoDate = currentDate.toISOString();
console.log(currentDate, isoDate);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-23
    • 2010-09-07
    • 2021-05-21
    • 2010-12-21
    • 1970-01-01
    • 2019-08-24
    相关资源
    最近更新 更多