javascript - DateTimeFormat 是否考虑夏令时?

标签 javascript

我正在将一些依赖于 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_YorkEurope/LondonEurope/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/

相关文章:

javascript - 将变量传递给在 for 循环中创建的 click 函数

javascript - Math.sqrt() 返回无穷大?

javascript - 使用reduceRight删除数组中的最后一个元素

javascript - 以 Angular 方式将工厂注入(inject) Controller 中

javascript - 如何获取NetSuite上的所有项目列表?

javascript - 多个下拉菜单的纯javascript显示/隐藏

javascript - 没有使用 node.js 连接到数据库

javascript - HTML5 canvas 上下文不能用 clearRect() 清除

javascript - string.indexOf ("*.") 在 Javascript 中做什么?

javascript - 无法通过内容脚本使用 jQuery 更改 HTML 元素的样式