簡體   English   中英

使用 JavaScript 顯示特定時區的實時時間

[英]Display Live Time for Specific Time Zone using 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();

使用Intl.DateTimeFormat Api

 let 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 time = new Date().toLocaleString("en-US", { timeZone: "Asia/Dhaka" });
function checkTime(i) {
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}

function startTime() {
  var asiaDhaka = new Date().toLocaleString([], { timeZone: "Asia/Dhaka" });
  var today = new Date(asiaDhaka);

  var h = today.getHours();
  var m = today.getMinutes();
  var s = today.getSeconds();
  // add a zero in front of numbers<10
  var isFormat12H = true;
  var ampm = "";
  if (isFormat12H) {
    ampm = h >= 12 ? "pm" : "am";
    h = h % 12;
    h = h ? h : 12;
  }
  m = checkTime(m);
  s = checkTime(s);
  document.getElementById("time").innerHTML = h + ":" + m + ":" + s + ampm;
  t = setTimeout(function () {
    startTime();
  }, 1000);
}
startTime();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM