我可以根据 $time_zone1 制作一个显示正确时间的时钟。到目前为止,一切都很好。唯一的问题是时钟不会每秒更新,或者根本不会更新。我一直在努力解决在 javascript 中创建时间的解决方案(而不是使用 $current_time_formatted),但这不起作用,因为 javascript 总是使用 我的当地时间而不是 $time_zone1 中设置的时间创建时钟。
<?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>
您可以使用 Intl.DateTimeFormat
在 JavaScript 中设置特定时区的时间<!-- Display the clock -->
<div id="clock"><?php echo $current_time_formatted; ?> America/New_York</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: 'America/New_York',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
},
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()) + ' America/New_York';
}
// Update the clock every second
setInterval(updateTime, 1000);
})
</script>