i have a date variable like this const date=new Date() and when i console.log this it shows me Tue May 02 2017 11:35:50 GMT+0300 (GTB Daylight Time) which is correct of course. I want to convert this to Iso Date and i'm using toIsoString() function of javascript like this:
const IsoDate = (date.toISOString()).slice(0, -5);
console.log(IsoDate)
but it shows me in the console this: 2017-05-02T08:35:50 It seems that it shows 3 hours before the actual date. Why is this happening?
If you want to use toISOString but get the current date in your timezone, you can adjust the UTC minutes by your offset first, then add the timezone string, e.g.
function toISOStringLocal(date) {
// Copy date so don't modify original
var d = new Date(+date);
var offset = d.getTimezoneOffset();
var sign = offset < 0? '+' : '-';
// Subtract offset as ECMAScript offsets are opposite to usual
d.setUTCMinutes(d.getUTCMinutes() - d.getTimezoneOffset());
// Convert offset to string
offset = ('0' + (offset/60 | 0)).slice(-2) + ('0' + (offset%60)).slice(-2);
return d.toISOString().replace(/Z\s*/i,'') + sign + offset;
}
console.log('Current date: ' + toISOStringLocal(new Date()));
You could also add methods to the Date prototype:
// Return local date in ISO 8601 format
if (!Date.prototype.toISOStringLocal) {
Date.prototype.toISOStringLocal = function() {
var d = new Date(+this);
var offset = d.getTimezoneOffset();
var sign = offset < 0? '+' : '-';
d.setUTCMinutes(d.getUTCMinutes() - d.getTimezoneOffset());
offset = ('0' + (offset/60 | 0)).slice(-2) + ('0' + (offset%60)).slice(-2);
return d.toISOString().replace(/Z\s*/i,'') + sign + offset;
};
}
// Return UTC date in ISO 8601 format
if (!Date.prototype.toISODate) {
Date.prototype.toISODate = function() {
return d.toISOString().substr(0,10);
};
}
var d = new Date();
console.log('The current local date is: ' + d.toISOStringLocal() +
'\nThe current UTC date is : ' + d.toISODate()
);