Lessy Lessy - 1 year ago 125
Javascript Question

Converting String date to Date object

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

. When I do a


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

d = new Date(activity.ActivityDate);

I get an invalid date. But when I do

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

I do get a proper date object.

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

Answer Source

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