0

I have this php:

<?php
$mytestdate = "Oct 23, 2019 20:00:00";
?>

This javascript does not give me the required output:

<script>
var mydate = "<?php echo $mytestdate; ?>";
// Set the date we're counting down to
var countDownDate = new Date(mydate).getTime();
</script>

This javascript does give me the desired output:

<script>
var mydate = "<?php echo $mytestdate; ?>";
// Set the date we're counting down to
var countDownDate = new Date("Oct 23, 2019 20:00:00").getTime();
</script>

What is going wrong?!

The output is either nothing or "NaNd NaNh NaNm NaNs".

10
  • 1
    you should never mix PHP and JS - they're different languages that get executed differently Commented Oct 21, 2019 at 13:35
  • what does your (html) source reveal? Commented Oct 21, 2019 at 13:36
  • try console.log(mydate) and see what is in there first, from there, you can know what's going wrong Commented Oct 21, 2019 at 13:39
  • From where does your mytestdate comes from Commented Oct 21, 2019 at 13:40
  • 1
    i hope this will help u: stackoverflow.com/questions/46109832/… Commented Oct 21, 2019 at 13:46

1 Answer 1

3

So when you try to run this code in a HTML file you get NaN as you are claiming,

<!DOCTYPE html>
<html>
<body>
  <?php
   $mytestdate = "Oct 23, 2019 20:00:00";
  ?>
<script>
  var mydate = "<?php echo $mytestdate; ?>";
  var countDownDate = new Date(mydate).getTime();
  alert(countDownDate);
</script>

</body>
</html>

Now, try to save this in a file with .php extension. The code will work and return you the expected result

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

10 Comments

<script> var mydate = "<?php echo $mytestdate; ?>"; console.log(mydate); // Set the date we're counting down to var countDownDate = new Date(mydate).getTime();</script>
This is what is showing in the browser source. It does not seem to output the php.
@NeilReardon: so it means, your file extension is .PHP not .HTML right?
store your variable in a hidden input then get this hidden input value in your javascript @NeilReardon
@BilalSiddiqui: i like your answer ...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.