使用 JavaScript 显示特定时区的实时时间

任何人都可以在下面帮助我。


我有显示实时时间的 JavaScript 代码,它需要系统当前时间,但我想显示特定时区(亚洲/达卡)的时间。我怎样才能用这段代码做到这一点?


function checkTime(i) {

  if (i < 10) {

    i = "0" + i;

  }

  return i;

}


function startTime() {

  var today = new Date();

  var h = today.getHours();

  var m = today.getMinutes();

  var s = today.getSeconds();

  // add a zero in front of numbers<10

  m = checkTime(m);

  s = checkTime(s);

  document.getElementById('time').innerHTML = h + ":" + m + ":" + s;

  t = setTimeout(function() {

    startTime()

  }, 500);

}

startTime();


莫回无
浏览 143回答 3
3回答

阿晨1998

function checkTime(i) {&nbsp; if (i < 10) {&nbsp; &nbsp; i = "0" + i;&nbsp; }&nbsp; return i;}function startTime() {&nbsp; var asiaDhaka = new Date().toLocaleString([], { timeZone: "Asia/Dhaka" });&nbsp; var today = new Date(asiaDhaka);&nbsp; var h = today.getHours();&nbsp; var m = today.getMinutes();&nbsp; var s = today.getSeconds();&nbsp; // add a zero in front of numbers<10&nbsp; var isFormat12H = true;&nbsp; var ampm = "";&nbsp; if (isFormat12H) {&nbsp; &nbsp; ampm = h >= 12 ? "pm" : "am";&nbsp; &nbsp; h = h % 12;&nbsp; &nbsp; h = h ? h : 12;&nbsp; }&nbsp; m = checkTime(m);&nbsp; s = checkTime(s);&nbsp; document.getElementById("time").innerHTML = h + ":" + m + ":" + s + ampm;&nbsp; t = setTimeout(function () {&nbsp; &nbsp; startTime();&nbsp; }, 1000);}startTime();

当年话下

使用Intl.DateTimeFormat APIlet options = {    timeZone: 'Asia/Dhaka',    year: 'numeric',    month: 'numeric',    day: 'numeric',    hour: 'numeric',    minute: 'numeric',    second: 'numeric',  },  myDate = new Intl.DateTimeFormat([], options);setInterval(() => {  console.log(myDate.format(new Date()));}, 1000);您可能需要检查浏览器支持

桃花长相依

用这个:let&nbsp;time&nbsp;=&nbsp;new&nbsp;Date().toLocaleString("en-US",&nbsp;{&nbsp;timeZone:&nbsp;"Asia/Dhaka"&nbsp;});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript