'Get date ISO string without time in javascript
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)?
Solution 1:[1]
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.
Solution 2:[2]
var isoDate = new Date().toISOString().substring(0,10);
console.log(isoDate);
Solution 3:[3]
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'));
Solution 4:[4]
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();
Solution 5:[5]
with date-fns format
import {format} from "date-fns-tz"
format(new Date(), 'yyyy-MM-dd')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | mikemaccana |
| Solution 3 | czuhajster |
| Solution 4 | yglodt |
| Solution 5 | panchicore |
