I have date type column in MS SQL table, which I need to convert to full date and time in JavaScript. Here is my code:
$.ajax({
type: "POST",
url: "http://localhost:8080/dates",
data: {},
dataType: "JSON",
success: function(data) {
holidays = new Array();
for (var i of data[0])
{
date = new Date(i.holiday_date);
console.log(date);
holidays.push(date);
}
}
});
The result is:
Mon May 01 2017 03:00:00 GMT+0300 (FLE Summer Time)
Tue May 02 2017 03:00:00 GMT+0300 (FLE Summer Time)
My question is why it is adding three hours?
You are probably passing an ISO 8601 date YYYY-MM-DD to the Date object, and those are treated as UTC time. Thus, when converted to local time, 3 hours are added. The same would happen if you're passing unix timestamps.
Now, you shouldn't just add or remove 3 hours somewhere to correct for it, since it will break twice a year with daylight savings time.
The best way would be to either use a full ISO 8601 timestamp YYYY-MM-DDTHH:mm:ss.sssZ, e.g. 2017-05-02T00:00:00+03:00, or use separate parameters for the Date object constructor because in that case those are treated as local time, not UTC:
new Date(year, month, day);
More about Date objects here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
As far as I can find, you can get a full ISO 8601 timestamp out of SQL Server like this:
CONVERT(VARCHAR(24), GETDATE(), 127)
because the result date is not in your time zone, take at look the date format Mon May 01 2017 03:00:00 GMT+0300 (FLE Summer Time) ,GMT+0300means add three hours.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With