Get date ISO string without time in javascript
If you can live with depending on the great momentjs.com library, it will be as easy as this:
moment().format('YYYY-MM-DD');
or
moment().toISOString();
If you want your code to be logically persistent, a substring based on hard coded indexes is never safe:
var iso = date.toISOString();
iso = iso.substring(0, iso.indexOf('T'));
Just use setUTCHours
instead of setHours
and compensate for timezone:
var date = new Date();
var timezoneOffset = date.getMinutes() + date.getTimezoneOffset();
var timestamp = date.getTime() + timezoneOffset * 1000;
var correctDate = new Date(timestamp);
correctDate.setUTCHours(0, 0, 0, 0);
document.write(correctDate.toISOString())
setHours
will set time in your local timezone, but when you display it, it will show the time in UTC. If you just set it as UTC from the beginning, you'll get the result you want.
EDIT:
Just be aware that if you are ahead of UTC, your date will be stored as a UTC date from the previous day, so running setUTCHours
will not work as intended, changing your date to midnight of the previous day. Therefore, you first need to add the timezone offset to the date.
var isoDate = new Date().toISOString().substring(0,10);
console.log(isoDate);