Search code examples
javascriptphp

Make clock update in real time by passing variable from PHP to javascript


I can make a clock appearing with correct time based on $time_zone1. So far so good. The only problem is that the clock does not update every second - or at all. I have struggled with solution where time is created in javascript (instead of using $current_time_formatted), but that did not work as javascript always created clock using my local time instead of the time set in $time_zone1.

Also, I want to be able to change 'America/New_York' to other time zone. So, in PHP, I will fetch a certain time zone, say that now $time_zone='Europe/London'. So, somehow I have to tell javascript to create clock for 'Europe/London', instead of 'America/New_York'. That is,

$time_zone1 = new DateTime('now', new DateTimeZone($time_zone))
<?php
// Create a DateTime object for the current time
// 'America/New_York', 'Europe/London', 'Asia/Tokyo'
$time_zone1 = new DateTime('now', new DateTimeZone('America/New_York'));

// Format the current time
$current_time_formatted = $time_zone1->format('H:i:s');
?>

<!-- Display the clock -->
<div id="clock"><?php echo $current_time_formatted; ?> America/New_York</div>

<!-- JavaScript for updating the clock -->
<script>
function updateTime() {
    // Get the clock element
    var clock = document.getElementById('clock');
    
    // Update the clock display using the PHP variable directly
    clock.innerHTML = '<?php echo $current_time_formatted; ?>' + ' America/New_York';
}

// Update the clock every second
setInterval(updateTime, 1000);
</script>

Solution

  • You can make the time in JavaScript for a specific timezone using Intl.DateTimeFormat

    <?php
    $time_zone = "America/New_York";
    ?>
    
    <!-- Display the clock -->
    <div id="clock"> <?php echo $time_zone; ?></div>
    
    <!-- JavaScript for updating the clock -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <script>
        $(document).ready(function() {
            function updateTime() {
                let options = {
                    timeZone: "<?php echo $time_zone; ?>",
                    timeStyle: 'medium',
                };
    
                formatter = new Intl.DateTimeFormat([], options);
    
                // Get the clock element
                var clock = document.getElementById('clock');
    
                // Update the clock display using the PHP variable directly
                clock.innerHTML = formatter.format(new Date()) + ' <?php echo $time_zone; ?>';
            }
    
            // Update the clock every second
            setInterval(updateTime, 1000);
        })
    </script>