moment.js is great but sometimes you don't want to pull a large number of dependencies for simple things.
The following works as well:
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);
console.log(localISOTime) // => '2015-01-26T06:40:36.181'
The slice(0, -1) gets rid of the trailing Z which represents Zulu timezone and can be replaced by your own.
moment.js is great but sometimes you don't want to pull a large number of dependencies for simple things.
The following works as well:
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);
console.log(localISOTime) // => '2015-01-26T06:40:36.181'
The slice(0, -1) gets rid of the trailing Z which represents Zulu timezone and can be replaced by your own.
My solution without using moment is to convert it to a timestamp, add the timezone offset, then convert back to a date object, and then run the toISOString()
var date = new Date(); // Or the date you'd like converted.
var isoDateTime = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();
It's very unclear what you're asking. If you want the UTC date with the hours always 0, then set the UTC hours to 0 and use toISOString, e.g.
var d = new Date();
d.setUTCHours(0,0,0,0);
console.log(d.toISOString());
Of course this is going to show the UTC date, which may be different to the date on the system that generated the Date.
Also,
new Date('2017-04-27').toISOString();
should return 2017-04-27T00:00:00Z (i.e. it should be parsed as UTC according to ECMA-262, which is contrary to ISO 8601 which would treat it as local), however that is not reliable in all implementations in use.
If you just want to get the current date in ISO 8601 format, you can do:
if (!Date.prototype.toISODate) {
Date.prototype.toISODate = function() {
return this.getFullYear() + '-' +
('0'+ (this.getMonth()+1)).slice(-2) + '-' +
('0'+ this.getDate()).slice(-2);
}
}
console.log(new Date().toISODate());
However, since the built-in toISOString uses UTC this might be confusing. If the UTC date is required, then:
if (!Date.prototype.toUTCDate) {
Date.prototype.toUTCDate = function() {
return this.getUTCFullYear() + '-' +
('0'+ (this.getUTCMonth()+1)).slice(-2) + '-' +
('0'+ this.getUTCDate()).slice(-2);
}
}
console.log(new Date().toUTCDate());
old_date = Fri Jan 08 2021 16:01:30 GMT+0900
const new_date = old_date.toISOString().substring(0, 10);
new_date = "2021-01-08"