我正在将一些依赖于 moment-timezone
的时间检查转换为使用 INTL.DateTimeFormat
。
对于上下文,代码采用以毫秒为单位的用户当前时间 (Date.now()
),并根据三个时区(每个网站都有自己的区域设置)检查它:
const formatter = Intl.DateTimeFormat([], {
timeZone: timezone,
year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric',
minute: 'numeric', second: 'numeric',
})
时区是 America/New_York
、Europe/London
或 Europe/Madrid
。 Formatter 被传递到 Date.parse
以将其转换为适当的 ms
格式。
我在确定函数是否已经考虑夏令时时遇到了一些麻烦。如果不是,我可以在其他地方做一些逻辑来转换我将比较的两个时间与适当的 DST 值。
这是已经存在的东西吗?它是在引擎盖下,还是函数第一个参数的一部分?只是无法在文档中找到信息。
最佳答案
试试这个:
<html>
<head>
<script language="JavaScript">
// 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
d = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time in " + city + " is " + nd.toLocaleString();
}
alert(calcTime('New York ', '-4'));
alert(calcTime('Madrid', '+1'));
alert(calcTime('London', '+1'));
</script>
</head>
<body>
</body>
</html>
关于javascript - DateTimeFormat 是否考虑夏令时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53935691/