【问题标题】:Changing list of time zone offset numbers to current times with JavaScript使用 JavaScript 将时区偏移量列表更改为当前时间
【发布时间】:2021-01-20 21:57:00
【问题描述】:

我正在表格中显示名称列表及其时区偏移数字。偏移量数字是它们的时区与 UTC 的偏移量。我需要使用 JavaScript 或 jQuery 更改所有偏移数字以显示该人所在时区的当前时间。

我希望发生的事情是将偏移量数字替换为 calcTime 函数中的当前日期/时间......知道我做错了什么吗?

这是我的代码:

<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>

【问题讨论】:

  • 我不确定您要完成什么。您是否尝试调整日期时间以在不同的时区显示?
  • 抱歉,我会调整一下问题。基本上,我们有一个他们的时区与 UTC 的偏移量列表。我需要在他们的名字旁边显示那个人的当地时间。
  • 该代码存在一些逻辑问题,无法按所写的那样工作。但是,第一次通过(即使此代码可以工作),-57曾经在 HTML 元素中 中的任何 offset 已经替换为字符串。第二次通过该字符串产生无效日期(因为它不再是 偏移量)。
  • @RandyCasburn 感谢您的回复。我知道 calcTime 函数有效,因为我在其他地方找到了它并对其进行了测试,但是我在时区 div 中循环的代码不起作用,因为我是一个 javascript 菜鸟,我不知道如何修复它。 .
  • 您正在遍历具有“时区”类的元素,试图在这些元素中找到具有“时区”类的元素。

标签: javascript html jquery


【解决方案1】:

我认为这就是您试图实现的目标(进行重大更改)。

注意setInterval() 的使用,而不是设置超时和对 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>

【讨论】:

  • 哇,这真的很接近!看起来此代码正在添加(或减去)本地时间的偏移量,而不是 UTC 时间。有没有办法让它使用UTC?
  • 是的 - 抱歉,忘记本地偏移量。现在应该进行编辑。
  • 我在 GMT-5 时区...显示的“John Doe”时间差了 2 小时。
  • EDT 对我来说很划算。现在它显示 UTC 时间为 12:42,美国东部时间 (-5) 时间为 7:42。 @LouysPatriceBessette
  • @LouysPatriceBessette - 是的,我是减去负数而不是加数。所以这是固定的。但我不明白两个小时的差异。请立即尝试。
【解决方案2】:

在 @RandyCasburn 的帮助下,我得以完成这项工作:

$(document).ready(function() {
     const collection = document.querySelectorAll('.timezone');
     const outputs = document.querySelectorAll('.output');

     function calcTime(offset) {
         d = new Date();
         utc = d.getTime() + (d.getTimezoneOffset() * 60000);
         nd = new Date(utc + (3600000*offset));
         return nd.toLocaleString();
     }
     setInterval(() => {
        collection.forEach((element, idx) => {
           outputs[idx].textContent = calcTime(element.textContent);
           $(".timezone").hide();
        });
    });
});

<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>

非常感谢!

【讨论】:

  • 我编辑了我的答案 - 请考虑支持并接受我的答案。谢谢,
【解决方案3】:

如果我正确解决了问题.. .oO(lol)
您希望根据他们的 UTC 偏移量显示每个用户的实时时间。

我会在数据属性中包含用户时区,以确保方便使用。
(请参阅下面的 HTML 中所做的更改)
那么:

  • 创建本地时间对象(页面呈现的位置)
  • 从本地时间,您可以获得 UTC 偏移量和本地小时。
  • 计算页面查看器与“其他用户”之间的偏移量。
    含义...作为页面查看器,我处于 ​​GMT-5 时区,第一个用户(在您的 HTML 中)与我的偏移量为零。正确吗?
  • 所以从本地时间和本地GMT偏移量开始,加上“实时时差”
  • 可悲的是,.setHours() 方法返回毫秒...所以用它创建一个新的日期对象。
  • 将其转换为字符串并删除“GMT-...”之后的部分,因为这部分现在不准确。

这是一个包含所有 console.logs 的演示:

console.clear();

$(document).ready(function () {
  function calcTime(offset) {
    // That is a date object with the user's timezone
    let refDate = new Date();

    // So what is the user's timezone?
    let userTimezone = refDate.getTimezoneOffset() / 60;
    console.log("userTimezone", userTimezone);

    // What is the user's Hour?
    let localHour = refDate.getHours();
    console.log("localHour", localHour);

    // Make the calculation here
    let timeZoneDiff = offset + userTimezone;
    console.log("timeZoneDiff", timeZoneDiff);

    // Set the hour... But we still are in a "timezoned object"
    // and the .setHours returns milliseconds. ;(
    let hourRearanged = refDate.setHours(localHour + timeZoneDiff);
    console.log("hourRearanged", hourRearanged);

    // So re-generate a date object from that "arranged hour"
    let semiResult = new Date(hourRearanged).toString();
    console.log("semiResult were the part after GMT is wrong:", semiResult);

    console.log("---------------------------------------");
    
    // Rturn the part before "GMT"
    return semiResult.split("GMT")[0];
  }

  setInterval(() => {
    $(".name").each(function (index, element) {
      h = parseInt($(element).data("timezone"));
      $(element).next(".userTime").html(calcTime(h));
    });
  }, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="name" data-timezone="-5">John Doe (GMT-5)</div>
<div class="userTime">-5</div>
<div class="name" data-timezone="3">Jane Doe (GMT+3)</div>
<div class="userTime">3</div>
<div class="name" data-timezone="7">Jim Smith (GMT+7)</div>
<div class="userTime">7</div>
<div class="name" data-timezone="-3">Cathy Jones (GMT-3)</div>
<div class="userTime">-3</div>

请以全页模式运行...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 2013-07-19
    • 2020-09-11
    • 2015-03-11
    相关资源
    最近更新 更多