Lessy Lessy - 5 months ago 37
Javascript Question

Converting String date to Date object

I have a variable which is retrieved from php, and is stored in a variable called

activity.ActivityDate
. When I do a

console.log(activity.ActivityDate);


It outputs
14/06/2016
, which is a valid format which can be turned into a date object. But when I do

d = new Date(activity.ActivityDate);
console.log(d);


I get an invalid date. But when I do

e = new Date('14/06/2016');
console.log(e);


I do get a proper date object.

Is there something wrong with my
activity.ActivityDate
string, or some way to turn it into a proper string?

Answer

Different browsers can parse datestrings differently as noted by MDN it's discouraged to use the Date() constructor to parse a datestring. In your case you're giving the format DD/MM/YYYY, but it's likely your browser is expecting MM/DD/YYYY.

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

The best thing to do so it would work in all browsers would be to spilt your string by "/" and convert your numbers into integers then use the constructor format for the Date(year, month, day) constructor.

For example:

var date = '14/06/2016';
var items = date.split('/');
var day = +items[0];            // Note +(item) means convert to interger
var month= +(items[1] - 1);     // month goes from 0-11 rather than 1-12.
var year = +items[2];
e = new Date(year, month, day);
console.log(e);