【问题标题】:Check Date Range with a place that uses Daylight Savings in Javascript在 Javascript 中使用夏令时检查日期范围
【发布时间】:2021-02-24 23:57:35
【问题描述】:

Javascript 中有没有办法检查具有给定经度/纬度和城市的位置是否使用夏令时?

我目前正在遍历来自不同位置的对象列表,需要以秒为单位计算它们的日期范围。

【问题讨论】:

    标签: javascript timezone dst timezone-offset


    【解决方案1】:

    我们可以使用tz-lookup 模块根据位置的经纬度来确定 IANA 时区,如下所示。

    我已切换到使用 Luxon 模块来获取每个位置的 UTC 偏移量(以分钟为单位)。一旦你有了这个,你应该能够得到每个城市之间的差异。

    let IANAZone = luxon.IANAZone;
    let locations = [
        { lat: -33.865, lng: 151.209444, name: "Sydney"},
        { lat: 51.507222, lng: -0.1275, name: "London" },
        { lat: 42.7235, lng: -73.6931, name: "New York" },
        { lat: 39.739167, lng: -104.990278, name: "Denver"},
        { lat: 34.05, lng: -118.25, name: "Los Angeles"}
    ];
    
    locations = locations.map(loc => ( { ...loc, timeZone: tzlookup(loc.lat, loc.lng) }));
       
    let rows = [["Location", "Timezone", "UTC Offset (min)", "Current time"], ...locations.map(({ name, timeZone }) => [name , timeZone, IANAZone.create(timeZone).offset(new Date()) + "", new Date().toLocaleString('sv', { timeZone })])];
    rows = rows.map(row => row.map(s => s.padEnd(20)).join(""))
    rows.forEach(row => console.log(row))
    <script src="https://cdn.jsdelivr.net/npm/tz-lookup@6.1.25/tz.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.25.0/luxon.min.js"></script>

    【讨论】:

    • padEnd(20) 是做什么的或者我在哪里可以阅读到这个?
    • 刚刚更新了我想要应用此方法的问题,这样做是否有意义: new Date(endDate).toLocaleString('sv', { timeZone } - new Date (startDate).toLocaleString('sv', { timeZone } ?
    • 是的,我在不同的时区有不同的位置,所以当我计算范围时,有些会有额外/更少的小时,而有些则没有。我要测试一下谢谢!
    • 结果证明它不起作用。它不转换对象(仅字符串):/
    • @TerryLennox - 不要将toLocaleString 的字符串输出传递给Date 构造函数。 Date 构造函数会将其解释为 本地时间 - 而不是您想要的时区。最终Date 对象不能代表其他时区。您需要一个库,例如 Luxon
    【解决方案2】:

    这个问题似乎对你有一些有用的信息。

    How to get a time zone from a location using latitude and longitude coordinates?

    【讨论】:

      猜你喜欢
      • 2015-01-22
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2022-10-16
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 2014-07-25
      相关资源
      最近更新 更多