Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 649
Maximus Decimus Avatar asked Apr 20 '17 19:04

Maximus Decimus


3 Answers

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'));
like image 190
Alexandre Daubricourt Avatar answered Oct 18 '22 19:10

Alexandre Daubricourt


var isoDate = new Date().toISOString().substring(0,10);
console.log(isoDate);
like image 21
Diego Avatar answered Oct 18 '22 18:10

Diego


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.

like image 8
Pedro Castilho Avatar answered Oct 18 '22 18:10

Pedro Castilho