问题描述
我正在表中显示名称及其时区偏移量的列表.偏移量数字是其时区与UTC的偏移量.我需要使用JavaScript或jQuery更改所有偏移量数字以显示该人所在时区的当前时间.
I am displaying a list of names and their time zone offset numbers in a table. The offset numbers are their time zone's offset from UTC. I need to change all of the offset numbers to show the current time in the person's time zone using JavaScript or jQuery.
我想发生的是,偏移量将被 calcTime
函数中的当前日期/时间替换...知道我在做什么错吗?
What I would like to happen is the offset numbers would be replaced with the current date/time from the calcTime
function... any idea what I'm doing wrong?
这是我的代码:
<div class="name">John Doe</div><div class="timezone">-5</div>
<div class="name">Jane Doe</div><div class="timezone">3</div>
<div class="name">Jim Smith</div><div class="timezone">7</div>
<div class="name">Cathy Jones</div><div class="timezone">-3</div>
<script>
$(document).ready(function() {
setTimeout(() => {
function calcTime(offset) {
// create Date object for current location
d = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time is " + nd.toLocaleString();
}
$(".timezone").each(function(){
h = $(this).find(".timezone").text();
element.innerHTML = calcTime(h);
//alert(calcTime('-5'));
});
}, 1000);
});
</script>
推荐答案
我认为这是您要实现的目标(有很大的变化).
I think this is what you are attempting to achieve (with significant changes).
请注意使用 setInterval()
而不是设置超时和HTML的结构更改.
Note the use of setInterval()
rather than set time out and the structural changes to the HTML.
const utc = document.querySelector('.utc');
const collection = document.querySelectorAll('.timezone');
const outputs = document.querySelectorAll('.output');
const localeTZoffSet = new Date().getTimezoneOffset()/60 * 3600000;
setInterval(() => {
utc.textContent = calcTime(0);
collection.forEach((element, idx) => {
outputs[idx].textContent = calcTime(element.textContent);
});
});
function calcTime(offset) {
return "The local time is " + new Date(Date.now() + localeTZoffSet + (3600000 * offset)).toLocaleTimeString();
}
<div>UTC: <span class="utc"></span></div>
<div class="name">John Doe - <span class="output"></span></div>
<div class="timezone">-5</div>
<div class="name">Jane Doe - <span class="output"></span></div>
<div class="timezone">3</div>
<div class="name">Jim Smith - <span class="output"></span></div>
<div class="timezone">7</div>
<div class="name">Cathy Jones - <span class="output"></span></div>
<div class="timezone">-3</div>
这篇关于使用JavaScript将时区偏移量列表更改为当前时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!