JavaScript 如何将日期转换为另一个时区
JavaScript具有一个新的Date()构造函数,用于创建日期对象以获取当前日期和时间。此日期对象使用UTC时区或客户端浏览器的时区,即如果您在印度使用new Date()构造函数获取日期和时间,则将获得本地时间。但是有时,我们可能需要获取另一个国家的时区,这是我们无法直接做到的。这可以通过使用toLocaleString()方法或format()方法来实现。在本文结束时,您将能够在JavaScript中获取任何其他时区的日期。
本文中我们将使用的两种将日期转换为另一个时区的方法如下−
- 使用toLocaleString()方法
-
使用format()方法
使用toLocaleString()方法
可以使用日期对象调用toLocaleString()方法。此方法具有根据传入的参数从一个时区转换数据到另一个时区的能力。它接受两个参数,第一个是“locale”,用于指定要使用的语言的格式约定,对于英语,它是“en-US”,第二个是“options”,对于我们而言,它是{timeZone:”countryName”},其中countryName是我们要为其更改时区的国家的名称。
以下是使用toLocaleString()方法在JavaScript中将日期转换为另一个时区的步骤。
- 使用Date构造函数创建日期对象
-
使用toLocaleString()方法和第一个参数作为’en-US’来为英语语言日期和时间格式进行转换,并使用第二个参数{timeZone: “America/New_York”}来获取纽约的时区
-
将此方法返回的值存储在变量中,该变量是我们需要的时区。
示例
在此示例中,我们将使用toLocaleString()方法在JavaScript中将日期转换为另一个时区。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Converting date to another timezone in JavaScript</title>
</head>
<body>
<h3>Convert date to America/New_York Time Zone using toLocaleString() Method</h3>
<p id="input">Local Time: </p>
<p id="output">America/New_York Time Zone: </p>
<script>
// date objec
let date = new Date();
document.getElementById("input").innerText += date ;
// convert date to another timezone
let output = date.toLocaleString("en-US", {
timeZone: "America/New_York"
});
// display the result
document.getElementById("output").innerText += output;
</script>
</body>
</html>
使用format()方法
可以使用format()方法与”Intl.DateTimeFormat”对象一起使用,并将日期对象作为参数传递给format()方法,将时区转换为在创建”Intl.DateTimeFormat”对象时传递的时区。如果你看下面的示例,它听起来很复杂,但实际上非常简单。
以下是使用format()方法将日期转换为其他时区的JavaScript步骤。
- 使用Date构造函数创建一个日期对象。
-
创建”Intl.DateTimeFormat”对象,第一个参数以’en-US’设置为英语日期和时间格式,第二个参数{timeZone: “America/New_York”}用于获取纽约的时区。
-
使用这个对象的format()方法,并将日期对象作为参数传递,并将其存储在一个变量中,该变量是我们所需的时区。
示例
在此示例中,我们使用format()方法将日期转换为JavaScript中的另一个时区。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Convert date to America/New_York timezone in JavaScript</title>
</head>
<body>
<h3>Convert date to America/New_York timezone using format() Method</h3>
<p id="input">Local Time: </p>
<p id="output">America/New_York Time Zone: </p>
<script>
// date objec
let date = new Date();
document.getElementById("input").innerText += date ;
// create a new date object
let newObj = Intl.DateTimeFormat('en-US', {
timeZone: "America/New_York"
})
// convert date to another timezone
let newDate = newObj.format(date);
// display the result
document.getElementById("output").innerHTML += newDate;
</script>
</body>
</html>
总结
在本教程中我们总结了我们学到的内容。我们可以用两种方法将日期转换到另一个时区,第一种方法是使用date对象的toLocaleString()方法,第二种是使用格式化()方法与”Intl.DateTimeFormat”对象。这两种方法有不同的用途,您可以根据需求选择。我们推荐使用toLocaleString()方法,它易于使用并且需要比使用格式化()方法与”Intl.DateTimeFormat”对象少得多的代码行数。