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>
2
Answers
You can make the time in JavaScript for a specific timezone using Intl.DateTimeFormat
You could extend the idea of a simple clock using a simple
custom-component
so that all the clock functionality is self-contained and easily customisable using PHP to write the necessary timezone to the HTML element.The custom-component class uses the Intl.DateTimeFormat to render the time in your selected format, again customisable by editing the dataset attributes for the component.