具有特定格式和 GMT 的 JQuery 更新日期

问题描述

我只是使用我在 stackoverflow 上找到的 JQuery 函数来更新时间:

$(document).ready(function () {

  var serverTime = new Date();

  function updateTime() {
    /// Increment serverTime by 1 second and update the html for '#time'
    serverTime = new Date(serverTime.getTime() + 1000);
    $('#actual_time').html(serverTime);
  }

  $(function() {
    updateTime();
    setInterval(updateTime,1000);
  });

})

但现在我正在尝试使用这样的代码更改格式,但没有成功。

serverTime2 = new $.format.date(new Date(serverTime.getTime() + 1000),'g:i A')

我想将日期格式更改为“g:i A”,并且我还想将特定的 GMT 应用到我的日期,而不是 serverTime

你能帮我吗?

解决方法

这里不需要 JQuery。尝试使用 toLocaleTimeString

const locale24HourTime = (tz,date) => date.toLocaleTimeString("en-EN",{
    timeZone: tz,hourCycle: 'h23',hour: "2-digit",minute: "2-digit",second: "2-digit" });

const date1 = new Date();
console.log(`Atlantic/Reykjavik: ${locale24HourTime(`Atlantic/Reykjavik`,date1)}`);
console.log(`Asia/Kolkata: ${locale24HourTime(`Asia/Kolkata`,date1)}`);
console.log(`Asia/Shanghai: ${locale24HourTime(`Asia/Shanghai`,date1)}`);
console.log(`Europe/London: ${locale24HourTime(`Europe/London`,date1)}`);