-1

I have a column start_date in my database which is of type date, now i am trying to pass this data into my javascript function but it returns other data. I tried this: Send PHP date to JavaScript date format but it doesn't work on my case. My data looks like 2019-11-21 and my function gives me this Thu Jan 01 1987 03:00:00 GMT+1000 which is very far from my actual data. This is my javascript function:

function manageActionType(action, start_date){
    console.log(new Date(Date.parse(start_date)));
}
Anirudh Lou
  • 781
  • 2
  • 10
  • 28
  • don't forget to quote the `start_date` when passing it to your javascript `Date` functions as it is a string – Professor Abronsius Nov 24 '19 at 12:19
  • I already have this on my html: `````` – Anirudh Lou Nov 24 '19 at 12:23
  • 1
    There are no quotes around the PHP variable. Would be more like `onclick="manageActionType('Step A', '{{ $process->start_date }}')"` ~ notice quotes around php variable!! – Professor Abronsius Nov 24 '19 at 12:24
  • 1
    Also see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) as "2019-11-21" will be parsed as UTC. The use of *Date.parse* is redundant, `new Date(start_date)` is sufficient. – RobG Nov 24 '19 at 22:33

1 Answers1

1

Taking the stated date 2019-11-21 as a simple string variable in PHP it needs to be properly quoted in Javascript - otherwise you will get the invalid / unexpected date that you mention. Consider the following:

<?php
    $d='2019-11-21';
    echo "
    let d1=$d;
    let d2='$d';";
?>
console.info( new Date( Date.parse( d1 ) ) );
console.info( new Date( Date.parse( d2 ) ) );

 let d1=2019-11-21;
 let d2='2019-11-21';
 
 console.info( new Date( Date.parse( d1 ) ) );
 console.info( new Date( Date.parse( d2 ) ) );
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46