在 JavaScript 中将日期转换为另一个时区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10087819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:48:35  来源:igfitidea点击:

Convert date to another timezone in JavaScript

javascripttimezone

提问by Rizky Ramadhan

I am looking for a function to convert date in one timezone to another.

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

It need two parameters,

它需要两个参数,

  • date (in format "2012/04/10 10:10:30 +0000")
  • timezone string ("Asia/Jakarta")
  • 日期(格式为“2012/04/10 10:10:30 +0000”)
  • 时区字符串(“亚洲/雅加达”)

The timezone string is described in http://en.wikipedia.org/wiki/Zone.tab

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

Is there an easy way to do this?

是否有捷径可寻?

采纳答案by Udhaya

var aestTime = new Date().toLocaleString("en-US", {timeZone: "Australia/Brisbane"});
console.log('AEST time: '+ (new Date(aestTime)).toISOString())

var asiaTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Shanghai"});
console.log('Asia time: '+ (new Date(asiaTime)).toISOString())

var usaTime = new Date().toLocaleString("en-US", {timeZone: "America/New_York"});
console.log('USA time: '+ (new Date(usaTime)).toISOString())

var indiaTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Kolkata"});
console.log('India time: '+ (new Date(indiaTime)).toISOString())

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

回答by Brian Di Palma

For moment.jsusers, you can now use moment-timezone. Using it, your function would look something like this:

对于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);
}

回答by Valli69

Stolen shamelessly from: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329

无耻地从: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();

    // convert to msec
    // add local time zone offset
    // get UTC time in msec
    var utc = d.getTime() + (d.getTimezoneOffset() * 60000);

    // 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();
}

this function is useful to calculate time zone value by providing name of a city/country and offset value

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

回答by lambinator

Most desktop (not mobile) browsers except Safari support the toLocaleStringfunction with arguments, older browsers usually ignore the arguments.

除了 Safari 之外,大多数桌面(非移动)浏览器都支持带参数的toLocaleString函数,较旧的浏览器通常会忽略这些参数。

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

回答by Rizky Ramadhan

Okay, found it!

好的,找到了!

I'm using timezone-js. this is the code:

我正在使用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

回答by Endless

If you don't want to import some big library you could just use Intl.DateTimeFormatto convert Date objects to different timezones.

如果您不想导入一些大型库,您可以使用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 formater = new Intl.DateTimeFormat('sv-SE', options)
const startingDate = new Date("2012/04/10 10:10:30 +0000")

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

Offsets, daylight saving, and changes in the past will be taken care of for you.

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

回答by Cedric Simon

Got it !

知道了 !

Wanted to force the date shown = server date, no mattter the local settings (UTC).

无论本地设置(UTC)如何,都想强制显示日期=服务器日期。

My server is GMT-6 --> new Date().getTimezoneOffset() = 360.

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

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

回答by Codemaker

You can use to toLocaleString() method for setting the timezone.

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

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

For India you can use "Indian/Christmas" and the following are the various timeZones,

对于印度,您可以使用“Indian/Christmas”,以下是不同的时区,

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

回答by Santiago Corredtheitroada

If you just need to convert timezones I have uploaded a stripped-down versionof moment-timezonewith just the bare minimum functionallity. Its ~1KB + data:

如果你只需要转换时区,我已经上传了一个精简版时刻时区,只有最低限度的功能。它的 ~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());

回答by seeking27

I should note that I am restricted with respect to which external libraries that I can use. moment.js and timezone-js were NOT an option for me.

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

The js date object that I have is in UTC. I needed to get the date AND time from this date in a specific timezone('America/Chicago' in my case).

我拥有的 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 is currently 6 hours ahead of 'America/Chicago'. Output is:

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

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

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