Is there a way to obtain a ISO string of a new date type in javascript with time at midnight without rebuilding a new date with date parts nor formatting it?
I've been trying this
var date = new Date();
date.setHours(0, 0, 0, 0);
document.write(date.toISOString());
and I am getting this
2017-04-20T04:00:00.000Z
I want to get this
2017-04-20T00:00:00.000Z
Is there a built-in function or way as I 've been trying to do to get the desired output (with rebuilding a date object with the date parts)?
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'));
var isoDate = new Date().toISOString().substring(0,10);
console.log(isoDate);
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.
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