BN83 BN83 - 3 years ago 72
Ajax Question

Date in variable reading as "Invalid Date"

Using the following:

var timestart = $('.thisDiv').data("timestart");
var startDateTime = new Date(timestart);


to collect a date from a php file that is updating by ajax from this:

$TimeStart = date( 'Y,m,d,g,i', $TimeStart );

<div class="thisDiv" data-timestart="<?= $TimeStart ?>"></div>

var timestart = $('.thisDiv').data("timestart");


In console I'm getting the following when logging
timestart
and
startDateTime
:

2017,07,24,7,50
Invalid Date


If I paste the date that is output as follows

var startDateTime = new Date(2017,07,24,7,50);


Then it works fine. Any ideas why I'm getting Invalid Date?

Answer Source

Your timestart variable (JavaScript) is just a string. So it's a string 2017,07,24,7,50, and not those elements in order - which can't be used as separate parameters like new Date() expects.

Let's take a look at it!

var startDateTime = new Date(2017,07,24,7,50);   // Parameters in order - all OK!
var startDateTime = new Date("2017,07,24,7,50"); // A single string - single parameter, not OK!

You need to return a proper format of dates from PHP with...

$TimeStart = date('Y-m-d H:i:s', $TimeStart);

This would return a format such as 2017-07-24 21:08:32, which is of a valid format - both in PHP and JavaScript.

Alternatively, you can use a splat/spread-operator ... and split the string it into elements, like this

var timestart = $('.thisDiv').data("timestart");  // Get the string
timestart = timestart.split(",");                 // Split into array
var startDateTime = new Date(...timestart);       // Pass as arguments with splat-operator
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download