我有一个待办事项列表,存储在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

最佳答案

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);

关于javascript - 为什么我的日期从mysql在javascript中递减一天?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40774904/

10-12 00:05
查看更多