Devender Gupta
Devender Gupta

Reputation: 546

Pass date variable to Javascript function

I'm trying the find the difference in number of days between two dates. One of the date is the current date and another is the date from the php variable passed to the view page. When i try to display the date it shows invalid Date.

Below is code:

 function checkcurrent()
    {

      var last_date= new Date( {!! json_encode($medic->end_day) !!});
      var new_last_date = new Date(last_date.getFullYear(),last_date.getMonth(),last_date.getDate());

      var diff = parseInt((new_last_date - today) / (1000 * 60 * 60 * 24));
      window.alert(last_date);
    }

When i display just the {!! json_encode($medic->end_day) !!} it shows the date in the alert window. But when i pass it to the Date() it is not converted. When last_date is displayed in alert box it shows invalid date. Why is it? BTW the date im passing is of the format "23/08/2018" i.e "d/m/Y". Someone please help.

Upvotes: 0

Views: 1169

Answers (1)

Sang Nguyen
Sang Nguyen

Reputation: 1720

Try this code.

function checkcurrent()
{
  var today = new Date();
  var last_date= new Date('{{ \Carbon\Carbon::createFromFormat('d/m/Y', $medic->end_day)->toDateString() }}');
  var new_last_date = new Date(last_date.getFullYear(),last_date.getMonth(),last_date.getDate());

  var diff = parseInt((new_last_date - today) / (1000 * 60 * 60 * 24));
  window.alert(last_date);
}

I converted your date $medic->end_day to format Y-m-d. I've tested it and it works for me.

Upvotes: 1

Related Questions