【问题标题】:Convert date to another timezone in JavaScript在 JavaScript 中将日期转换为另一个时区
【发布时间】:2012-04-22 16:31:25
【问题描述】:

我正在寻找一种将一个时区中的日期转换为另一个时区的函数。

需要两个参数,

  • 日期(格式为“2012/04/10 10:10:30 +0000”)
  • 时区字符串(“亚洲/雅加达”)

时区字符串在http://en.wikipedia.org/wiki/Zone.tab中描述

有没有简单的方法可以做到这一点?

【问题讨论】:

标签: javascript timezone


【解决方案1】:

这里是单行:

function convertTZ(date, tzString) {
    return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));   
}

// usage: Asia/Jakarta is GMT+7
convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") // Tue Apr 20 2012 17:10:30 GMT+0700 (Western Indonesia Time)

// Resulting value is regular Date() object
const convertedDate = convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") 
convertedDate.getHours(); // 17

// Bonus: You can also put Date object to first arg
const date = new Date()
convertTZ(date, "Asia/Jakarta") // current date-time in jakarta.

   

这是MDN Reference

注意警告:上面的函数依靠解析 toLocaleString 结果来工作,它是在en-US locale 中格式化的日期字符串,例如"4/20/2012, 5:10:30 PM"。每个浏览器可能不接受 en-US 格式的日期字符串到它的 Date 构造函数,它可能会返回意外的结果(它可能会忽略夏令时)。

目前所有现代浏览器都接受这种格式并正确计算夏令时,它可能不适用于旧版浏览器和/或外来浏览器。

旁注:如果现代浏览器有 toLocaleDate 那就太好了 函数,所以我们不必使用这个 hacky 工作。

【讨论】:

  • 我更改了答案,因为这是正确且标准的方法,无需使用任何库。
  • MDN 文档明确指出,在所有实现中唯一需要识别的时区是 UTC。 (stackoverflow.com/questions/10087819/…) 在IE11中点击【运行代码sn-p】按钮会报错。
  • 这个答案显示正确地将时区传递给toLocaleString,但是它非常错误地显示将该字符串传递回Date 构造函数。那是自找麻烦。日期字符串解析器不需要接受特定于区域设置的格式,并且输入将被视为在本地时区中。不要那样做。只需使用第一个 toLocalString 调用的字符串输出即可。
  • @MattJohnson 那么你不能使用 getHour() 或者这样的方法
  • 这是一种有缺陷的方法。它不解析 OP 格式,它依赖于解析它们不需要解析的格式的浏览器,它可能会错误地应用夏令时偏移,并且它会将时间戳呈现为 UTC,而并非如此。 .toLocaleString(...) 部分可以,其余部分不行。
【解决方案2】:

对于moment.js 用户,您现在可以使用moment-timezone。使用它,您的函数将如下所示:

function toTimeZone(time, zone) {
    var format = 'YYYY/MM/DD HH:mm:ss ZZ';
    return moment(time, format).tz(zone).format(format);
}

【讨论】:

  • 我不确定如何添加新时区,文档没有帮助我。我只是一个程序员,不是时间专家!
  • 这里的问题是它没有返回一个新的 Date 对象,它返回一个字符串。如果这是你想要的,那当然很好。
  • 不就是“返回时刻(time).tz(zone).format(format);”吗? ?您在代码中给出的那个有“无效日期”错误。
  • 无法在浏览器中加载 Moment.js。很伤心:(
  • 如果您对使用 tz 数据库副本向浏览器发送 180K 不满意,并且可以忍受旧浏览器上的当前时区降级,请使用Date.prototype.toLocaleString 尝试@lambinator 的答案。
【解决方案3】:

Most browsers 支持带参数的toLocaleString 函数,旧版浏览器通常会忽略参数。

const str = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' });
console.log(str);

【讨论】:

  • Edge 和 chrome 喜欢它:)
  • 它刚刚在 Chrome v59 和 Firefox 桌面 v54 以及 Android v59 上的 Chome 和 iOS 10.3 上的 Safari 10 上运行。它在 IE10 上不起作用。 MDN's description of Date.prototype.toLocaleString() 有一个 toLocaleStringSupportsLocales() 实现,可让您可靠地检查支持。
  • 另外,在上述所有浏览器中,它们的格式与jsfiddle.net/pmorch/ptqwmbyu中显示的完全相同
  • 在 node.js v8.7.0 中测试成功
  • 不,这从当前时间开始,但问题是关于转换任意时间(& tz),这些是非常不同的 - 日期只是获取当前系统时间而无法覆盖它.
【解决方案4】:

无耻地盗取自:http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329

/** 
 * function to calculate local time
 * in a different city
 * given the city's UTC offset
 */
function calcTime(city, offset) {

    // create Date object for current location
    var d = new Date();
   
    // get UTC time in msec
    var utc = d.getTime();
   
    // create new Date object for different city
    // using supplied offset
    var nd = new Date(utc + (3600000*offset));
   
    // return time as a string
    return "The local time in " + city + " is " + nd.toLocaleString();
}

此函数可用于通过提供城市/国家名称和偏移值来计算时区值

【讨论】:

  • 不错....但我认为他希望根据传入的城市为他查找偏移量。
  • 这不考虑夏令时变化。
  • 不回答问题,但回答了我的问题 (+1)
  • 那个'3600000'真的杀了我!在输入中, tz 应该以小时为单位!而且,应该减去。所以,如果你通过: var d=new Date calcTime('', d.getTimezoneOffset() / 60 );它应该同时回馈。
  • 这个答案严重过时,应该删除,特别是使用 toLocaleString 的部分,当它被转移到不同的时区时,它可能会报告主机时区。有更好的方法可以为不同的偏移量手动创建时间戳。
【解决方案5】:

好的,找到了!

我正在使用timezone-js。这是代码:

var dt = new timezoneJS.Date("2012/04/10 10:10:30 +0000", 'Europe/London');
dt.setTimezone("Asia/Jakarta");

console.debug(dt); //return formatted date-time in asia/jakarta

【讨论】:

  • 我必须对此投反对票,timezone-js 不支持 DST,并且它没有在其自述文件中宣传这一点,这对于寻找这个的人来说是一个不好的提示。请参阅:github.com/mde/timezone-js/issues/51 以及许多其他已提交但似乎尚未修复的问题。
  • @nus 是的,但是对于客户端时区/日期管理确实没有解决方案......因此,jquery ui datepicker 一直让我发疯。干杯
  • @Marabunta,看起来像时刻时区(由 Brian Di Palma 回答)支持 DST github.com/moment/moment-timezone/issues/21
  • 不要使用 TimezoneJS,它在 DST 更改方面存在问题。
【解决方案6】:

如果您不想导入一些大型库,您可以使用 Intl.DateTimeFormat 将 Date 对象转换为不同的时区。

// Specifying timeZone is what causes the conversion, the rest is just formatting
const options = {
  year: '2-digit', month: '2-digit', day: '2-digit',
  hour: '2-digit', minute: '2-digit', second: '2-digit',
  timeZone: 'Asia/Jakarta',
  timeZoneName: 'short'
}
const formatter = new Intl.DateTimeFormat('sv-SE', options)
const startingDate = new Date("2012/04/10 10:10:30 +0000")

const dateInNewTimezone = formatter.format(startingDate) 
console.log(dateInNewTimezone) // 12-04-10 17:10:30 GMT+7

将为您处理偏移、夏令时和过去的变化。

【讨论】:

  • IE10+ 不支持时区的 Intl API。 moment.github.io/luxon/docs/manual/matrix.html
  • 这其实是最好的答案。 toLocaleString 的实现不一致,从 IE11 开始有效。
  • 仅供参考:这实际上在 IE11 中不起作用,至少在 Windows 8.1 上是这样。当您尝试创建formatter 对象时,您会得到:```'timeZone' 的选项值'Asia/Jakarta' 超出有效范围。预期:['UTC'] ```
  • 有没有办法将格式化程序的最终结果再次转换为 Date 对象?
  • 这非常适合我的需求。就支持而言,如果不需要 IE,it's at 96%,所以对我来说这已经足够了。 @mding5692 使用 new Date(Date.parse(new Intl.DateTimeFormat(...))),但请注意 Date.parse 仅是 ES5 及更高版本。
【解决方案7】:

知道了!

想要强制显示日期 = 服务器日期,与本地设置 (UTC) 无关。

我的服务器是 GMT-6 --> new Date().getTimezoneOffset() = 360

myTZO = 360;
myNewDate = new Date(myOldDateObj.getTime() + (60000*(myOldDateObj.getTimezoneOffset()-myTZO)));
alert(myNewDate);

【讨论】:

  • 虽然它显示了正确的原始时间,但仍保留了来自 myOldDateObj 的时区信息。所以实际上是错误的时间(当你把时间作为时间而不是手表上的时间时)。
  • @gabn88 : 您将无法使用 Javascript 更改服务器时间...要修复服务器时间,请在操作系统级别进行。
  • 我不需要修复服务器时间;)服务器时间对我来说始终是 UTC。但我在不同的时区有不同的组织。他们的设备应始终显示其组织驻扎的时间,无论他们身在何处。
  • 我们有类似的问题,总是显示日期 X 时区。我们尝试从服务器以字符串格式发送所有日期,在浏览器中我们只是将它们视为本地时区日期。
  • 是否有可靠的方法来获得偏移量,它考虑夏令时?
【解决方案8】:

您可以使用 toLocaleString() 方法来设置时区。

new Date().toLocaleString('en-US', { timeZone: 'Indian/Christmas' })

对于印度,您可以使用“Indian/Christmas”,以下是各个时区,

"Antarctica/Davis",
    "Asia/Bangkok",
    "Asia/Hovd",
    "Asia/Jakarta",
    "Asia/Phnom_Penh",
    "Asia/Pontianak",
    "Asia/Saigon",
    "Asia/Vientiane",
    "Etc/GMT-7",
    "Indian/Christmas"

【讨论】:

  • 您不是在设置 timeZone,而是在生成一个以该 timeZone 表示的时间的字符串。日期保持不变。
  • toLocaleString 解决方案是 already given 4 years ago
  • "Etc/GMT-7" - 是一个非常有用的值。
  • India/ChristmasChristmas Island(位于印度洋的澳大利亚领土)的时区标识符。对于印度,首选时区标识符是 Asia/Kolkata
【解决方案9】:

我应该注意,我在可以使用哪些外部库方面受到限制。 moment.js 和 timezone-js 不适合我。

我拥有的 js 日期对象是 UTC。我需要在特定时区(在我的情况下为“美国/芝加哥”)中的该日期获取日期和时间。

 var currentUtcTime = new Date(); // This is in UTC

 // Converts the UTC time to a locale specific format, including adjusting for timezone.
 var currentDateTimeCentralTimeZone = new Date(currentUtcTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));

 console.log('currentUtcTime: ' + currentUtcTime.toLocaleDateString());
 console.log('currentUtcTime Hour: ' + currentUtcTime.getHours());
 console.log('currentUtcTime Minute: ' + currentUtcTime.getMinutes());
 console.log('currentDateTimeCentralTimeZone: ' +        currentDateTimeCentralTimeZone.toLocaleDateString());
 console.log('currentDateTimeCentralTimeZone Hour: ' + currentDateTimeCentralTimeZone.getHours());
 console.log('currentDateTimeCentralTimeZone Minute: ' + currentDateTimeCentralTimeZone.getMinutes());

UTC 目前比“美国/芝加哥”早 6 小时。输出是:

currentUtcTime: 11/25/2016
currentUtcTime Hour: 16
currentUtcTime Minute: 15

currentDateTimeCentralTimeZone: 11/25/2016
currentDateTimeCentralTimeZone Hour: 10
currentDateTimeCentralTimeZone Minute: 15

【讨论】:

  • new Date(); 返回本地时区,而不是 UTC
  • 来自文档:If no arguments are provided, the constructor creates a JavaScript Date object for the current date and time according to system settings.
  • 嗯。有点混乱。这不会更改日期的时区;而是使用更改的时间创建一个新日期。使用正则表达式从 toLocaleString 调用创建的字符串中提取所需的值会更清晰。
  • 似乎不可靠。这可能适用于美国中部时间的用户,他们的浏览器设置为美国语言环境,但是当夏令时开始或结束时它会在其他地方中断(因为时间更改将在不同的时间),并且至少有一些 JS解释器使用机器设置的语言环境解析日期字符串。
【解决方案10】:

如果您只需要转换时区,我已经上传了 stripped-down versionmoment-timezone,仅具有最低限度的功能。它的 ~1KB + 数据:

S.loadData({
    "zones": [
        "Europe/Paris|CET CEST|-10 -20|01010101010101010101010|1GNB0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0|11e6",
        "Australia/Sydney|AEDT AEST|-b0 -a0|01010101010101010101010|1GQg0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0|40e5",
    ],
    "links": [
        "Europe/Paris|Europe/Madrid",
    ]
});

let d = new Date();
console.log(S.tz(d, "Europe/Madrid").toLocaleString());
console.log(S.tz(d, "Australia/Sydney").toLocaleString());

【讨论】:

  • 这是一个定时炸弹……它会在夏令时规则发生变化时破裂,这种情况一直在发生。
  • @michael-scheper 当然,您需要保持区域数据是最新的。
【解决方案11】:

这是我的代码,它运行良好,你可以试试下面的演示:

$(document).ready(function() {
   //EST
setInterval( function() {
var estTime = new Date();
 var currentDateTimeCentralTimeZone = new Date(estTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));
var seconds = currentDateTimeCentralTimeZone.getSeconds();
var minutes = currentDateTimeCentralTimeZone.getMinutes();
var hours =  currentDateTimeCentralTimeZone.getHours()+1;//new Date().getHours();
 var am_pm = currentDateTimeCentralTimeZone.getHours() >= 12 ? "PM" : "AM";

if (hours < 10){
     hours = "0" + hours;
}

if (minutes < 10){
     minutes = "0" + minutes;
}
if (seconds < 10){
     seconds = "0" + seconds;
}
    var mid='PM';
    if(hours==0){ //At 00 hours we need to show 12 am
    hours=12;
    }
    else if(hours>12)
    {
    hours=hours%12;
    mid='AM';
    }
    var x3 = hours+':'+minutes+':'+seconds +' '+am_pm
// Add a leading zero to seconds value
$("#sec").html(x3);
},1000);


});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<p class="date_time"><strong id="sec"></strong></p>
</body>
</html>

【讨论】:

  • 欢迎来到 StackOverflow!您能否提供更多信息,例如此代码的工作原理及其作用?它是如何解决问题的?
  • 我上面给出的代码是将您的时区更新为其他国家/地区的时区。
  • 您需要将 HTML 放入您的 html 文件中,并且上面给出的 jquery 代码需要在页脚中。它会根据 ('en-US', { timeZone: 'America/Chicago' }) 你需要更新这两个值,如果你想要其他国家的时区谢谢
  • 不用等待。我只是在没有仔细看的情况下对此表示赞同。为什么要在 currentDateTimeCentralTimeZone.getHours() 上加 1?没有它,它会起作用,并且与 seek27 的答案 stackoverflow.com/a/40809160/1404185 相同
  • '它工作得很好'——你确定吗?您是否在多个时区、一年中的不同时间(因此有不同的夏令时规则)、不同的语言环境(包括默认的美国语言环境,其日期格式令人困惑)对其进行了测试?我肯定遇到过在解析new Date(string) 时使用系统语言环境的 JS 解释器,所以强制使用 AM/PM 时间和美国格式的日期是在自找麻烦恕我直言。
【解决方案12】:

yearmonthday设置一个变量,用-符号分隔,加上THH:mm:ss模式中的时间,然后字符串末尾的+01:00(在我的情况下,时区是+1)。然后将此字符串用作日期构造函数的参数。

// desired format: 2001-02-04T08:16:32+01:00
dateAndTime = year+"-"+month+"-"+day+"T"+hour+":"+minutes+":00+01:00";

var date = new Date(dateAndTime );

【讨论】:

    【解决方案13】:

    我不知道将日期对象转换为任何时区的简单方法,但是如果要将其转换为本地时区,则可以将其与Date.prototype.getTime()转换为相应的毫秒数,然后再回来。

    date = new Date('2016-05-24T13:07:20');
    date = new Date(date.getTime());
    

    例如,如果您和我一样在奥地利(现在是夏天),date.getHours() 现在将返回 15 而不是 13

    我了解到,各种日期时间函数在某些浏览器中可能会表现出非标准行为,因此请先对此进行测试。我可以确认它在 Chrome 中有效。

    【讨论】:

    • 为什么这被否决了?这是迄今为止最简单和最好的方法。上面的大多数答案都没有考虑夏季/冬季时间
    • 第二行有什么意义? Date 构造函数已经假定您的本地时区。这两行都返回本地浏览器时区的日期,并且没有回答有关如何转换为具有夏令时的另一个时区的问题。
    【解决方案14】:

    您也可以尝试将日期时区转换为印度:

    var indianTimeZoneVal = new Date().toLocaleString('en-US', {timeZone: 'Asia/Kolkata'});
    var indainDateObj = new Date(indianTimeZoneVal);
    indainDateObj.setHours(indainDateObj.getHours() + 5);
    indainDateObj.setMinutes(indainDateObj.getMinutes() + 30);
    console.log(indainDateObj);
    

    【讨论】:

    • 在第 2 步之后,我有时间在印度......那你为什么还要加 5&1/2hrs 呢?
    • 使用该方法时,当我使用 Chrome 进行控制台日志时,我在挪威得到以下信息:原文:Thu Sep 27 2018 15:53:46 GMT+0200 (sentraleuropeisk sommertid)。修改时间:2018 年 9 月 27 日星期四 19:23:46 GMT+0200 (sentraleuropeisk sommertid)。 “sentraleuropeisk sommertid”是指中欧夏令时。不确定当您在印度需要夏季时间时这是否有效,或者当您在印度并且需要欧洲的夏季时间时反之亦然,等等。
    • 像这样使用 setHours() 不会考虑日、月、年的转换,例如,新戴尔 8 日凌晨 3:30 是伦敦 7 日晚上 11 点。然后考虑月末、年末和闰日。让 Date 做数学
       let local_time = new Date(zulu_time.getTime() + 3600000*std_timezone.timezone_factor - 60*60*1000);让 date_str = local_time.toISOString().slice(0, 10);让 time_str = local_time.toISOString().slice(11, -1);让 timezone_str = std_timezone.timezone_str; 
    【解决方案15】:

    我最近在 Typescript 中这样做了:

    // fromTimezone example : Europe/Paris, toTimezone example: Europe/London
    private calcTime( fromTimezone: string, toTimezone: string, dateFromTimezone: Date ): Date {
      const dateToGetOffset = new Date( 2018, 5, 1, 12 );
    
      const fromTimeString = dateToGetOffset.toLocaleTimeString( "en-UK", { timeZone: fromTimezone, hour12: false } );
      const toTimeString = dateToGetOffset.toLocaleTimeString( "en-UK", { timeZone: toTimezone, hour12: false } );
    
      const fromTimeHours: number = parseInt( fromTimeString.substr( 0, 2 ), 10 );
      const toTimeHours: number = parseInt( toTimeString.substr( 0, 2 ), 10 );
    
      const offset: number = fromTimeHours - toTimeHours;
    
      // convert to msec
      // add local time zone offset
      // get UTC time in msec
      const dateFromTimezoneUTC = Date.UTC( dateFromTimezone.getUTCFullYear(),
        dateFromTimezone.getUTCMonth(),
        dateFromTimezone.getUTCDate(),
        dateFromTimezone.getUTCHours(),
        dateFromTimezone.getUTCMinutes(),
        dateFromTimezone.getUTCSeconds(),
      );
    
      // create new Date object for different city
      // using supplied offset
      const dateUTC = new Date( dateFromTimezoneUTC + ( 3600000 * offset ) );
    
      // return time as a string
      return dateUTC;
    }
    

    我使用“en-UK”格式,因为它很简单。可能是“en-US”或任何可行的方法。

    如果第一个参数是您的语言环境时区,第二个参数是您的目标时区,它会返回一个具有正确偏移量的 Date 对象。

    【讨论】:

      【解决方案16】:

      环顾四周,包括此页面的链接,我发现这篇很棒的文章,使用时刻时区:

      https://www.webniraj.com/2016/11/23/javascript-using-moment-js-to-display-dates-times-in-users-timezone/

      总结一下:

      获取用户的时区

      var tz = moment.tz.guess();
      console.info('Timezone: ' + tz);
      

      返回例如:时区:欧洲/伦敦

      设置默认用户时区

      moment.tz.setDefault(tz);
      

      设置自定义时区

      moment.tz.setDefault('America/Los_Angeles');
      

      将日期/时间转换为本地时区,假设原始日期/时间为 UTC

      moment.utc('2016-12-25 07:00').tz(tz).format('ddd, Do MMMM YYYY, h:mma');
      

      返回:2016 年 12 月 25 日,星期日,早上 7:00

      将日期/时间转换为洛杉矶时间

      moment.utc('2016-12-25 07:00').tz('America/Los_Angeles').format('ddd, Do MMMM YYYY, h:mma');
      

      返回:2016 年 12 月 24 日星期六晚上 11:00

      从洛杉矶时间转换为伦敦时间

      moment.tz('2016-12-25 07:00', 'America/Los_Angeles').tz('Europe/London').format( 'ddd, Do MMMM YYYY, h:mma' );
      

      返回:2016 年 12 月 25 日星期日下午 3:00

      【讨论】:

        【解决方案17】:

        你也可以使用 https://www.npmjs.com/package/ctoc_timezone

        它有很多简单的实现和格式定制。

        在 toTimeZone 中改变格式:

        CtoC.toTimeZone(new Date(),"EST","Do MMM YYYY hh:mm:ss #{EST}");

        输出:

        28th Feb 2013 19:00:00 EST

        您可以在文档中探索多种功能。

        【讨论】:

          【解决方案18】:

          提供所需的时区,例如“亚洲/德黑兰”以将当前时间更改为该时区。我用的是“亚洲/首尔”。

          您可以使用以下代码。如果需要,请更改样式。

          请记住,如果您想使用 h:m:s 格式而不是 HH:MM:SS,则必须删除“function kcwcheckT(i)”。

          function kcwcheckT(i) {
            if (i < 10) {
              i = "0" + i;
            }
            return i;
          }
          function kcwt() {
          var d = new Date().toLocaleString("en-US", {timeZone: "Asia/Seoul"});
          d = new Date(d);
            var h = d.getHours();
            var m = d.getMinutes();
            var s = d.getSeconds();
            h = kcwcheckT(h);
            m = kcwcheckT(m);
            s = kcwcheckT(s);
            document.getElementById("kcwcurtime").innerHTML = h + ":" + m + ":" + s;
            var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
          document.getElementById("kcwcurday").innerHTML = days[d.getDay()]
          }
          kcwt();
          window.setInterval(kcwt, 1000);
          @import url('https://fonts.googleapis.com/css2?family=Nunito&display=swap');
          
          .kcwsource {color:#040505;cursor: pointer;display:block;width: 100%;border: none;border-radius:5px;text-align:center;padding: 5px 10px 5px 10px;}
          .kcwsource p {font-family: 'Nunito', sans-serif;}
          
          
          .CurTbx {color:#040505;cursor: pointer;display:block;width: 100%;border: none;border-radius:5px;text-align:center;padding: 5px 10px 5px 10px;}
          .kcwcstyle {font-family: 'Nunito', sans-serif; font-size: 22px;display: inline-block;}
          .kcwcurstinf {font-family: 'Nunito', sans-serif; font-size: 18px;display: inline-block;margin: 0;}
          .kcwcurday {margin: 0;}
          .kcwcurst {margin: 0 10px 0 5px;}
          
          /*Using the css below you can make your style responsive!*/
          
          @media (max-width: 600px){
            .kcwcstyle {font-size: 14px;}
            .kcwcurstinf {font-size: 12px;}
          }
          <div class="kcwsource"><p>This Pen was originally developed for <a href="http://kocowafa.com" target="_blank">KOCOWAFA.com</a></p></div>
          <div class="CurTbx"><p class="kcwcurst kcwcstyle" id="kcwcurday"></p><p class="kcwcurst kcwcstyle" id="kcwcurtime"></p><p class="kcwcurstinf">(Seoul, Korea)</p></div>

          【讨论】:

            【解决方案19】:

            做起来很简单:

            const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
            console.log(timeZone);
            
            var d = new Date();
            console.log(d.toLocaleString('en-US', { timeZone }));

            【讨论】:

            • 问题在于输出是一个字符串,而 JavaScript 似乎没有提供一种优雅、“简单”的方法来从字符串转换为时区初始日期,没有可能会被语言环境和夏令时问题搞砸。
            【解决方案20】:

            熟悉 java 8 java.time 包或 joda-time 的人可能会喜欢这个新的孩子:js-joda 库。

            安装

            npm install js-joda js-joda-timezone --save
            

            例子

            <script src="node_modules/js-joda/dist/js-joda.js"></script>
            <script src="node_modules/js-joda-timezone/dist/js-joda-timezone.js"></script>
            <script>
            var dateStr = '2012/04/10 10:10:30 +0000';
            JSJoda.use(JSJodaTimezone);
            var j = JSJoda;
            // https://js-joda.github.io/js-joda/esdoc/class/src/format/DateTimeFormatter.js~DateTimeFormatter.html#static-method-of-pattern
            var zonedDateTime = j.ZonedDateTime.parse(dateStr, j.DateTimeFormatter.ofPattern('yyyy/MM/dd HH:mm:ss xx'));
            var adjustedZonedDateTime = zonedDateTime.withZoneSameInstant(j.ZoneId.of('America/New_York'));
            console.log(zonedDateTime.toString(), '=>', adjustedZonedDateTime.toString());
            // 2012-04-10T10:10:30Z => 2012-04-10T06:10:30-04:00[America/New_York]
            </script>
            

            在真正的 Java 本质中,它非常冗长,哈哈。但是,作为一个移植的 java 库,特别是考虑到他们移植了 1800 多个测试用例,它也可能非常准确地工作。

            计时操作很难。这就是为什么许多其他库在边缘情况下存在缺陷的原因。 Moment.js 似乎得到了正确的时区,但我见过的其他 js 库,包括timezone-js,似乎并不值得信赖。

            【讨论】:

              【解决方案21】:

              我在使用 Moment Timezone 时遇到问题。我添加这个答案只是为了如果其他人面临同样的问题。所以我有一个来自我的API 的日期字符串2018-06-14 13:51:00。我知道它存储在UTC 中,但字符串本身并不能说明问题。

              我让时刻时区知道,这个日期来自哪个时区:

              let uTCDatetime = momentTz.tz("2018-06-14 13:51:00", "UTC").format();
              // If your datetime is from any other timezone then add that instead of "UTC"
              // this actually makes the date as : 2018-06-14T13:51:00Z
              

              现在我想通过以下方式将其转换为特定时区:

              let dateInMyTimeZone = momentTz.tz(uTCDatetime, "Asia/Kolkata").format("YYYY-MM-DD HH:mm:ss");
              // now this results into: 2018-06-14 19:21:00, which is the corresponding date in my timezone.
              

              【讨论】:

                【解决方案22】:

                只需设置您想要的国家时区,您就可以轻松地在 html 中显示它在每分钟后使用 SetInteval() 函数更新。函数 formatAMPM() 管理 12 小时格式和 AM/PM 时间显示。

                $(document).ready(function(){
                        var pakTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Karachi"});
                        pakTime = new Date(pakTime);
                
                        var libyaTime = new Date().toLocaleString("en-US", {timeZone: "Africa/Tripoli"});
                        libyaTime = new Date(libyaTime);
                
                
                
                         document.getElementById("pak").innerHTML = "PAK  "+formatAMPM(pakTime);
                         document.getElementById("ly").innerHTML = "LY   " +formatAMPM(libyaTime);
                
                        setInterval(function(today) {
                            var pakTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Karachi"});
                            pakTime = new Date(pakTime);
                
                            var libyaTime = new Date().toLocaleString("en-US", {timeZone: "Africa/Tripoli"});
                            libyaTime = new Date(libyaTime);
                
                
                           document.getElementById("pak").innerHTML = "PAK  "+formatAMPM(pakTime);
                           document.getElementById("ly").innerHTML = "LY  " +formatAMPM(libyaTime);
                
                        },10000);
                
                         function formatAMPM(date) {
                            var hours = date.getHours();
                            var minutes = date.getMinutes();
                            var ampm = hours >= 12 ? 'pm' : 'am';
                            hours = hours % 12;
                            hours = hours ? hours : 12; // the hour '0' should be '12'
                            minutes = minutes < 10 ? '0'+minutes : minutes;
                            var strTime = hours + ':' + minutes + ' ' + ampm;
                            return strTime;
                        }
                
                
                    });
                

                【讨论】:

                  【解决方案23】:

                  存在服务器问题选择 gmt+0000 标准时区,您可以通过在 javascript 中使用库 moment-timezone 来更改它

                  const moment = require("moment-timezone")
                  const dateNew = new Date()
                  const changeZone = moment(dateNew);
                  changeZone.tz("Asia/Karachi").format("ha z");
                  // here you can paste "your time zone string"
                  

                  【讨论】:

                    【解决方案24】:

                    所有这些答案都有些多余,但这对我来说可以获取具有特定小时偏移量的当前 Date 对象。

                     function hourToMs(hour)
                        {
                            return hour * 60 * 1000 * 60;
                        }
                        
                        function minToMs(min)
                        {
                            return min * 60 * 1000;
                        }
                        
                        function getCurrentDateByOffset(offset)
                        {
                            // Get the current timezone in milliseconds to reset back to GMT aka +0
                            let timezoneOffset = minToMs((new Date()).getTimezoneOffset());
                            
                            // get the desired offset in milliseconds, invert the value because javascript is dum
                            let desiredOffset = hourToMs(offset * -1);
                        
                            return new Date(Date.now() + timezoneOffset - desiredOffset);
                        }
                        
                        // -6 hours is central timezone
                        console.log("The time is: " + getCurrentDateByOffset(-6));

                    【讨论】:

                      【解决方案25】:

                      您可以使用一个名为 timezones.json 的 npm 模块。它基本上由一个 json 文件组成,其中包含有关夏令时和偏移信息的对象。

                      对于asia/jakarta,它可以返回这个对象:

                      {
                        "value": "SE Asia Standard Time",
                        "abbr": "SAST",
                        "offset": 7,
                        "isdst": false,
                        "text": "(UTC+07:00) Bangkok, Hanoi, Jakarta",
                        "utc": [
                          "Antarctica/Davis",
                          "Asia/Bangkok",
                          "Asia/Hovd",
                          "Asia/Jakarta",
                          "Asia/Phnom_Penh",
                          "Asia/Pontianak",
                          "Asia/Saigon",
                          "Asia/Vientiane",
                          "Etc/GMT-7",
                          "Indian/Christmas"
                        ]
                      }
                      

                      你可以在这里找到它:

                      https://github.com/dmfilipenko/timezones.json

                      https://www.npmjs.com/package/timezones.json

                      希望有用

                      【讨论】:

                        【解决方案26】:

                        使用 luxon 库:

                        import { DateTime } from "luxon";
                        
                        // Convert function:
                        const convertTz = (datetime, fromTz, toTz, format='yyyy-MM-dd HH:mm:ss') => {
                          return DateTime.fromFormat(datetime, format, { zone: fromTz }).setZone(toTz).toFormat(format);
                        }
                        
                        // Use it like this:
                        console.log(convertTz('2021-10-03 19:00:00', 'Europe/Lisbon', 'America/New_York'));
                        
                        

                        【讨论】:

                          【解决方案27】:

                          您当前时区的时区偏移量

                          date +%s -d '1 Jan 1970'
                          

                          对于我的 GMT+10 时区(澳大利亚),它返回 -36000

                          【讨论】:

                            【解决方案28】:

                            快速而肮脏的手动小时更改器和返回:

                            return new Date(new Date().setHours(new Date().getHours()+3)).getHours()
                            

                            【讨论】:

                            • 太脏(太乱)
                            猜你喜欢
                            • 2015-02-21
                            • 1970-01-01
                            • 1970-01-01
                            • 2017-02-08
                            • 2018-06-07
                            相关资源
                            最近更新 更多