-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)));
}
4
  • don't forget to quote the start_date when passing it to your javascript Date functions as it is a string Commented Nov 24, 2019 at 12:19
  • I already have this on my html: <input name="action_type" type="radio" id="stepa" value="Step A" onclick="manageActionType('Step A', {{ $process->start_date }})" required /> Commented Nov 24, 2019 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!! Commented Nov 24, 2019 at 12:24
  • 1
    Also see 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. Commented Nov 24, 2019 at 22:33

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.