DEV Community

Cover image for PHP/Laravel/JS Countdown Day, Hour, Minute, Second using JS
Arman Rahman
Arman Rahman

Posted on

PHP/Laravel/JS Countdown Day, Hour, Minute, Second using JS

Here I am showing for Laravel. You can pass you value like this -

<input type="hidden" value="{{ @$data['event']->start }}" id="event_start_date">
Enter fullscreen mode Exit fullscreen mode

Add this JS on you page.

<script>
    function updateCountdown(eventStartDate) {
      const now = new Date();
      const targetDate = new Date(eventStartDate);
      const timeDifference = targetDate - now;

      if (timeDifference > 0) {
        const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
        const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);

        $('#countdown_day').text(days);
        $('#countdown_hour').text(hours);
        $('#countdown_minute').text(minutes);
        $('#countdown_second').text(seconds);
      } else {
        document.getElementById("countdown").innerHTML = "<p>Event has already started!</p>";
      }
    }

    const eventStartDate = $('#event_start_date').val();
    console.log(eventStartDate);
    updateCountdown(eventStartDate);

    // Update the countdown every second
    setInterval(() => {
      updateCountdown(eventStartDate);
    }, 1000);
  </script>
Enter fullscreen mode Exit fullscreen mode

You can change $('#event_start_date').val(); for your any data. date format 2023-08-08 10:00:00

Top comments (0)