Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Pain12's avatar

Doing calculation in Js with php!?

Hey guys, I am trying to work with some data from the database or php in javascript.

What I tried in my blade.php

<?php
  	$timenow = date('H:m:s');

  	$timefrom = $post->timefrom;
 	$timeto = $post->timeto;
 ?>
<script>  
    var time = "<?php echo $timenow ?>";  // var time = "18:03:36";
    var timefrom = "<?php echo $timefrom ?>";  //  var timefrom = "04:04:00";
    var timeto = "<?php echo $timeto ?>";  // var timeto = "23:03:00"; 
    var timedif = "<?php echo $timeto ?> - <?php echo $timenow ?>"; // var timedif = "23:03:00 - 18:03:36"

    $("#{{$post->id}}").click(function(){
        alert(timedif); // alert("23:03:00 - 18:03:36")
    });
</script>

I first get the actual time in php since its way easier to do. The goal is to calculate a time difference. What I don't know is how to tell js to take the difference between the two times. Since for Js everything is a string.

What I tried is to convert the actual time and the time from the DB to an integer in PHP. And then calculate with it in js.

I do all that to tell jquery later that if a timeslot is met it should add or remove certain elements from a div.

0 likes
3 replies
owiesnama's avatar
Level 19

you can parse the datetime like so

let timeto = new Date(Date.parse("2020/3/26 <?php $timeto ?>"))
let timenow = new Date(Date.parse("2020/3/26 <?php $timenow ?>"))

$("#{{$post->id}}").click(function(){
	alert(timeto.getHours() - timenow.getHours())
})
1 like
Pain12's avatar

I will look into it. Yes, have nearly 0 experience with js =D What I though I also could do is to do it in php like this:

<?php
  $timenow = strtotime(date('H:m:s'));
 
  $timefrom = strtotime($post->timefrom);
  $timeto = strtotime($post->timeto);
  $timedif= abs($timeto -  $timenow)/(60*60);
  ?>

But somehow that dosent seems to smart. Since I later need to input it to js again

Please or to participate in this conversation.