JavaScript子串返回错误

I am using Joomla and attempting to use the substring() function to pull out the first 4 characters of my string. The issue I am having is that I get an error of

This is my syntax - how should I change it so that it functions in my Joomla set-up?

Uncaught TypeError: phpdate.substring is not a function

Here is syntax:

<?php
  $randardate = '20160301';
?>
<script>
  var phpdate = <?php echo $randardate; ?>;
  var yearfromphpdate = phpdate.substring(0,4);
</script>

Since you are pre processing a javascript file with PHP, without quotes your javascript file would look something like

var phpdate = 20160301;

You need to add quotations like this

var phpdate = '<?php echo $randardate; ?>';

So that when PHP is done processing your file, it will be a string, not an int.

var phpdate = '20160301';

Your stacktrace is being thrown because substring expects a string, not an int.

Add quotation to make phpdate a string.

var phpdate = '<?php echo $randardate; ?>';