random1234
random1234

Reputation: 827

Why is my date from mysql decrementing by one day in javascript?

I have a todo list that is stored in mysql database the columns stored are todoTitle and todoDate, when i print the todoDate to screen as you can see in the code below it will show the date decremented by one day, for example if the date in the database shows 2016-12-20 it will show 2016-12-19 on my website.

If you are wondering why the todoDate is made into string and then substring it is because if i would not do that it would print out like this: 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

Upvotes: 2

Views: 3829

Answers (1)

Wangot
Wangot

Reputation: 91

The Z means "zero hour offset" also known as "Zulu time" (UTC). When you are querying the date from the database there are two possible scenario that the date is change, either in the database layer or on the application layer, adjusting it to the timezone you are at.

So for example if the database setting save time automatically to UTC when you got the actual data it will be converted to your current time zone. But from your example 2016-12-20 is converted to 2016-12-19T23:00:00.000Z then I am assuming that your database setting on date is saving it in a certain timezone then converting it to UTC.

To fix it try adjusting your application logic or database setting, for me I rather do it on the application level and maintain the date in DB to be save to UTC.

Try this to see the difference and could give you hint on solving your issue:

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

Upvotes: 2

Related Questions