JavaScript HTML多时区时钟

4
我该如何将checkTime和checkMinute函数合并,以便在进行(m + 30)的偏移时,当m达到60时,h也会进入下一个小时。谢谢!
目前,我的代码可以告诉时间,并且可以在24小时制上接受小时偏移,但我的问题是它不允许我在+30分钟的偏移中更改代码,而我想要这种能力。
我的if语句没有给我想要的结果,即当分钟数达到60时,从+30的偏移开始,小时将进入下一个小时,而不仅仅影响分钟数。
我认为我需要将这两个函数结合起来,但不确定如何准确地做到这一点。

function addLeadingZero(n) {
  return n < 10 ? '0' + n : n;
}

function timeClock(timeZoneOffset) {
  var d = new Date();
  d.setHours(d.getUTCHours() + timeZoneOffset); // set time zone offset
  var h = d.getUTCHours();
  var m = d.getUTCMinutes();
  var s = d.getUTCSeconds();
  /*    h = h % 12;
      h = h ? h : 12; // replace '0' w/ '12'  */
  /*  h = checkHour(h)  */
  m = checkTime(m);
  s = checkTime(s);
  h = addLeadingZero(h);

  document.all["txt3"].innerHTML = /*+ checkHour*/ (h - 4) + ':' + m + ':' + s + ' ';
  document.all["txt1"].innerHTML = /*+ checkHour*/ (h + 3) + ':' + m + '' + ' ';
  document.all["txt2"].innerHTML = h + ':' + checkMinute(m + 30) + '' + ' ';
  document.all["txt4"].innerHTML = h + ':' + m + '' + ' ';
  document.all["txt5"].innerHTML = h + ':' + m + '' + ' ';
  setTimeout(function() {
    timeClock(timeZoneOffset)
  }, 500);
}

function checkTime(i) {
  var j = i;
  if (i < 10) {
    j = "0" + i;
  }
  return j;
}

function checkHour(i) {
  var j = i;
  if (i > 23) {
    j = j - 24;
  }
  if (i < 0) {
    j = "0" + i;
  }
  return j;
}

function checkMinute(i) {
  var j = i;
  if (i > 59) {
    j = j - 60;
  }
  if (i < 0) {
    j = "0" + i;
  }
  return j;
}

/* setInterval(function() {
      startTime();
      }, 500);
    })(jQuery);    */

window.onload = function() {
  timeClock(2);
}
<div id="txt3"></div>
<div id="txt1"></div>
<div id="txt2"></div>
<div id="txt4"></div>
<div id="txt5"></div>


1
document.all 是 IE 时代的遗留物,早在千禧年之前就已存在... 您的代码很容易更新到2020年。 - mplungjan
此外,为什么要使用checkTime,当你有addLeadingZero并且你没有使用checkHour呢? - mplungjan
@mplungjan 我该如何更新document.all?我不太熟悉其他方法。我已经删除了checkTime。我没有注意到它会重复添加addLeadingZero。 - Johnlovescode
@mplungjan 有没有办法让一个函数同时执行 addLeadingZero 和 checkHour 的功能? - Johnlovescode
我的答案甚至不需要 const pad = (num) => ("0" + num).slice(-2);,我写的是用来替换你的 addLeadingZero ;) - mplungjan
document.all在IE4之后就不再需要了。可以使用document.getElementById/document.geteElementsByName和document.getElementsByTagName,现在也可以使用document.querySelector或document.getElementById(如果有ID)。 - mplungjan
2个回答

5

准确地说:欢迎来到2020年 ;)

相关信息: -- 时区列表 -> https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

-- Date.toLocaleString用法 -> https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/toLocaleString

[编辑] 添加了军事时间(不带秒和:分隔符)

第一个版本包含民用和军用时间

const OptionsCivil    = { hour12:true,  hour:'numeric', minute:'2-digit', second:'2-digit' };  
const OptionsMilitary = { hour12:false, hour:'2-digit', minute:'2-digit' };

const CivilTime=(dt,dz)=>dt.toLocaleString("en-GB", {...OptionsCivil, timeZone:dz })

const MilitaryTime=(dt,dz)=>
  {
  let rep = dt.toLocaleString("en-US", {...OptionsMilitary, timeZone:dz }).replace(/:/g,'')
  return (rep==='0000') ? 2400 : rep.replace(/^24/, '00'); // specific browsers marmelade
  }

setInterval(() => {
  let d = new Date();
  document.querySelectorAll('.timZon')
            .forEach(el=> el.textContent = CivilTime(d, el.dataset.timeZone));
  document.querySelectorAll('.timZonM')
            .forEach(el=> el.textContent = MilitaryTime(d, el.dataset.timeZone));
}, 1000);

/* or more concise :
setInterval(() => {
  let d = new Date();
  document.querySelectorAll('.timZon, .timZonM')
           .forEach(el=>el.textContent =(el.classList.contains('timZonM')?MilitaryTime:CivilTime)(d, el.dataset.timeZone));
}, 1000);
*/
div.timZon,
div.timZonM {
  width       : 7em;
  text-align  : right;
  margin      : .4em;
  color       : deeppink;
  font-family : 'Courier New', Courier, monospace;
}
div.timZonM { /* military time */
  width  : 3em;
  color  : navy;
}

/* css tooltip code for displaying timeZone value
   ----------------> irrelevant part, can be removed) */
div[data-time-zone] {
  cursor    : crosshair;
  position  : relative;
  }
div[data-time-zone]:hover {
  background-color : yellow;
  }
div[data-time-zone]:hover:before {
  position         : absolute;
  font-size        : .8em;
  top              : 1.7em;
  border-radius    : .8em;
  content          : 'TZ: ' attr(data-time-zone);
  background-color : darkblue;
  color            : whitesmoke;
  white-space      : nowrap;
  z-index          : 1000;
  padding          : .4em .6em;
  }
<div class="timZon"  data-time-zone="America/New_York" ></div>
<div class="timZonM" data-time-zone="America/New_York" ></div>
<div class="timZonM" data-time-zone="Asia/Kolkata"></div>
<div class="timZonM" data-time-zone="Europe/Paris"></div>
<div class="timZonM" data-time-zone="Australia/Adelaide"></div>
<div class="timZonM" data-time-zone="Etc/GMT"></div>
<div class="timZonM" data-time-zone="Etc/GMT+4"></div>
<div class="timZonM" data-time-zone="Etc/GMT-5"></div>



const OptionsMilitary = { hour12:false, hour:'2-digit', minute:'2-digit', second:'2-digit' };

const MilitaryTime=(elm, dt)=>
  {
  let [hh,mm,ss] = dt.toLocaleString("en-US", {...OptionsMilitary, timeZone:elm.dataset.timeZone }).split(':') 
  if ('seconds'in elm.dataset) elm.dataset.seconds = ':'+ss
  elm.textContent = (hh=='00'&&mm=='00') ? '2400' : (hh+mm).replace(/^24/, '00'); // specific browsers marmelade
  }

setInterval(() => {
  let dateTime = new Date();
  document.querySelectorAll('.timZonM').forEach(el=>MilitaryTime(el, dateTime));
}, 1000);
div.timZonM { /* military time */
  width          : 3em;
  margin         : .3em;
  color          : navy;
  font-size      : 20px;
  font-family    : 'Courier New', Courier, monospace;
  letter-spacing : .05em;
  }
div.timZonM::after {
  content : attr(data-seconds);
  color   : crimson;
  }

/* css tooltip code for displaying timeZone value
   ----------------> irrelevant part, can be removed) */
div[data-time-zone] {
  cursor    : crosshair;
  position  : relative;
  }
div[data-time-zone]:hover {
  background-color : yellow;
  }
div[data-time-zone]:hover:before {
  position         : absolute;
  font-size        : .8em;
  top              : 1.7em;
  border-radius    : .8em;
  content          : 'TZ: ' attr(data-time-zone);
  background-color : darkblue;
  color            : whitesmoke;
  white-space      : nowrap;
  z-index          : 1000;
  padding          : .4em .6em;
  }
<div class="timZonM" data-time-zone="America/New_York"></div>
<div class="timZonM" data-time-zone="Asia/Kolkata"></div>
<div class="timZonM" data-time-zone="Europe/Paris" data-seconds></div> <!-- add data-seconds to show seconds value -->
<!-- as much as you want... -->
<div class="timZonM" data-time-zone="Australia/Adelaide"></div>
<div class="timZonM" data-time-zone="Asia/Kathmandu"></div>
<div class="timZonM" data-time-zone="Etc/GMT"></div>
<div class="timZonM" data-time-zone="Etc/GMT+4" data-seconds></div>
<div class="timZonM" data-time-zone="Etc/GMT-5"></div>

要水平显示,请使用CSS的flex box

const OptionsMilitary = { hour12:false, hour:'2-digit', minute:'2-digit', second:'2-digit' }
  ,   timZonMil_All   = document.querySelectorAll('div.timZonMil > div')
  ;
const MilitaryTime=(elm, dt)=>
  {
  let [hh,mm,ss] = dt.toLocaleString("en-US", {...OptionsMilitary, timeZone:elm.dataset.timeZone }).split(':')
  elm.textContent = (hh=='00'&&mm=='00') ? '2400' : (hh+mm).replace(/^24/, '00'); // specific browsers marmelade
  if ('seconds' in elm.dataset) elm.innerHTML  += `<span>:${ss}</span>` 
  }
setInterval(() => {
  let dateTime = new Date();
  timZonMil_All.forEach(el=>MilitaryTime(el, dateTime));
}, 500);
div.timZonMil {
  display         : flex;
  justify-content : space-between;
  min-width       : 100vw;
  position        : absolute;
  top             : 123px;
  color           : navy;
  font-size       : 20px;
  font-family     : 'Courier New', Courier, monospace;
  letter-spacing  : .05em;
  }
div.timZonMil > div {
  min-width   : 3.6em;
  text-align  : center;
  }
div.timZonMil > div[data-seconds] {
  min-width   : 5.2em;
  }
div.timZonMil > div > span {
  color       : crimson;
  }

/* css tooltip code for displaying timeZone value
   ----------------> irrelevant part, can be removed) */
div[data-time-zone] {
  cursor    : crosshair;
  position  : relative;
  }
div[data-time-zone]:hover {
  background-color : yellow;
  }
div[data-time-zone]:hover:before {
  position         : absolute;
  font-size        : .8em;
  top              : 1.7em;
  border-radius    : .8em;
  content          : 'TZ: ' attr(data-time-zone);
  background-color : darkblue;
  color            : whitesmoke;
  white-space      : nowrap;
  z-index          : 1000;
  padding          : .4em .6em;
  }
<div class="timZonMil" >
  <div data-time-zone="Asia/Tehran"></div>
  <div data-time-zone="Etc/GMT"    ></div>
  <div data-time-zone="Etc/GMT+4"  data-seconds ></div>
  <div data-time-zone="Etc/GMT-8"  ></div>
  <div data-time-zone="Etc/GMT-14" ></div>
</div>

我也更改了第二种显示方法,针对你上一条消息。

太棒了!谢谢!如果我想进一步编辑时区,我应该在HTML中通过更改data-time-zone =“”为我想要的时区来实现吗? - Johnlovescode
return (rep==='0000') ? 2400 : rep.replace(/^24/, '00'); 的必要性是什么?JS默认使用基于0的24小时制时间。 - mplungjan
@Johnlovescode 这是因为 FireFox 显示 0000 而不是 2400,而 Chrome 显示 2403 而不是 0003,所以这段代码修正了这个问题。 - Mister Jojo
@MisterJojo 当然可以,请问如何验证您的代码,我是这个网站的新手。另外,我只想更改民用时间的显示方式,不显示上午或下午,但仍希望显示秒数。是否可能仅删除民用时间中的上午或下午并仍获取秒数,或者是否可能使用军用时间并添加秒数,因为最终我只想让其中一个时钟显示? - Johnlovescode
@MisterJojo 好的。谢谢。我也接受了你的答案。但是,我只想让粉色的民用时间以这种格式显示:1200:53,其中小时和分钟在一起,秒钟由“:”分隔,没有上午或下午的标识。 - Johnlovescode
显示剩余15条评论

2

欢迎来到2020年 ;)

对于HHMM军事时间,您可以使用

const pad = (num) => ("0" + num).slice(-2);
....
const [hh,mm,ss] = d.split(", ")[1].split(":");
document.querySelector("#" + t).innerHTML = pad(hh)+pad(mm)

const timeObj = {
  "txt1": {
    "tz": "America/New_York",
    "locale": "en-US"
  },
  "txt2": {
    "tz": "Asia/Kolkata",
    "locale": "en-IN"
  },
  "txt3": {
    "tz": "Europe/Berlin",
    "locale": "de-DE"
  }
};

const timeClock = () => {
  for (t in timeObj) {
    const tObj = timeObj[t];
    let d = new Date().toLocaleString(
      tObj.locale, { "timeZone": tObj.tz })
    document.querySelector("#" + t).innerHTML = d.split(", ")[1];
  }
};
setInterval(timeClock, 500);
div {
  width: 100px;
  text-align: right
}
<div id="txt1"></div>
<div id="txt2"></div>
<div id="txt3"></div>


@mplugjan 谢谢!这大大缩短了我的代码!唯一的问题是我需要军事时间,但我不确定如何更改您的编辑以获得该输出。 - Johnlovescode
1
转换为中文: - mplungjan
@Johnlovescode 我把语言设置从en_US改成了en_GB,这样你就可以使用24小时制了。 - mplungjan
@mplugjan 太好了。谢谢!我会试一下的。 - Johnlovescode
@Johnlovescode 你说的军事时间是指HHMM吗?如果是,看看这个简单更新。 - mplungjan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接