2016-11-23 27 views
0

我有一個待辦事項列表,存儲在MySQL數據庫中存儲的列是todoTitle和todoDate,當我將todoDate打印到屏幕上時,您可以在下面的代碼中看到它將顯示日期遞減一天,例如,如果數據庫中的日期顯示2016-12-20將在我的網站上顯示2016-12-19。爲什麼我的mysql的日期在javascript中減少了一天?

如果你想知道爲什麼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 
+0

時區應用?你看到23:00和'Z'全時間戳? –

+0

關於'.toStrong()。substring()',你不能格式化日期服務器端嗎?這將解決ISO日期字符串格式。另外,你能爲我提供一個'responseObject [i] .todoDate'的值和類型嗎? – amflare

+0

@VaoTsun它曾經是我的MySQL數據庫中的數據類型TIMESTAMP,但我將其更改爲DATE數據類型的列,並且它在我的數據庫中以YYYY-MM-DD格式保存,這正是我想要的,但是當我顯示它在網站上顯示全時間戳 – random1234

回答

0

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); 
相關問題