Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 890
user1665355 Avatar asked Mar 12 '16 15:03

user1665355


2 Answers

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/

like image 126
Matthijs Brouns Avatar answered Sep 25 '22 00:09

Matthijs Brouns


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.

like image 22
RobG Avatar answered Sep 22 '22 00:09

RobG