user1665355
user1665355

Reputation: 3393

Convert string to ISODate

How could I convert the string "2015-02-02" to ISODate 2015-02-02T00:00:00.000Z? I was trying to find some example but did not.

Upvotes: 22

Views: 54028

Answers (4)

Ahmed Adewale
Ahmed Adewale

Reputation: 3123

new Date("11/11/2019").toISOString()

or use it as a variable

mydate = "11/11/2019"
new Date(mydate).toISOString()

Upvotes: -1

RobG
RobG

Reputation: 147363

To change "2015-02-02" to "2015-02-02T00:00:00.000Z" simply append "T00:00:00.000Z":

console.log('2015-02-02' + 'T00:00:00.000Z');

Parsing to a Date and calling toISOString will fail in browsers that don't correctly parse ISO dates and those that don't have toISOString.

Upvotes: 2

Alex R
Alex R

Reputation: 624

new Date("2015-02-02").toISOString()

Upvotes: 2

Matthijs Brouns
Matthijs Brouns

Reputation: 2329

You can use the regular Javascript date functionality for this

new Date(dateString).toISOString()

from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

However, date parsing is very inconsistent across browsers so if you need this to be robust I would look into parsing using for example with Moment.js as this will allow you to specify a format string by which the date should be parsed like such

date = moment("12-25-1995", "YYYY-MM-DD");
date.format(); //will return an ISO representation of the date

from: http://momentjs.com/docs/#/parsing/string/

Upvotes: 26

Related Questions