【问题标题】:JavaScript - find date of next time change (Standard or Daylight)JavaScript - 查找下一次更改的日期(标准或日光)
【发布时间】:2010-12-08 09:44:23
【问题描述】:

这是一个及时的问题。北美*的时间变化规则是:

  • 11 月的第一个星期日,抵消对标准的更改(-1 小时)
  • 3 月的第二个星期日,日光偏移变化(与 GMT 的正常偏移)

考虑 JavaScript 中的一个函数,它接受一个 Date 参数,并且应该确定该参数是标准还是夏令时。

问题的根源是:

  • 您将如何构造下一次更改的日期?

算法/伪代码目前如下所示:

如果 argDate == "三月" { var firstOfMonth = new Date(); firstOfMonth.setFullYear(year,3,1); //星期几(0=星期日,6=星期六) var firstOfMonthDayOfWeek = firstOfMonth.getDay(); var firstSunday; if (firstOfMonthDayOfWeek != 0) //星期天! { //需要想办法确定哪个日期是第二个星期天 } }

这里的限制是使用标准的 JavaScript 函数,而不是抓取任何 JavaScript 引擎对 Date 对象的解析。这段代码不会在浏览器中运行,所以那些不错的解决方案将不适用。

**并非北美的所有地方/地区都会更改时间。*

【问题讨论】:

    标签: javascript algorithm datetime


    【解决方案1】:
    if argDate == "March" 
    {
    
        var firstOfMonth = new Date();
        firstOfMonth.setFullYear(year,3,1);
    
        //the day of week (0=Sunday, 6 = Saturday)
        var firstOfMonthDayOfWeek = firstOfMonth.getDay();
    
        var daysUntilFirstSunday =  (7-firstOfMonthDayOfWeek) % 7;
    
        var firstSunday = firstOfMonth.getDate() + daysUntilFirstSunday;
    
        // first Sunday now holds the desired day of the month
    }
    

    【讨论】:

      【解决方案2】:

      1) 我预计不同国家/地区可能会有其他一些规则。有些根本没有夏令时。因此,要在特定语言环境中找到答案,您可能会循环 365(6) 天以找到 getTimetoneOffset() 更改其值的日期。这在性能上应该不会有很大的滞后。

      2)然后,您可以获得时间变化的特定时间(美国凌晨 2 点?)。建议在 24 小时内再循环一次


      PS:好的,someone has already done the job =)。你应该在使用前测试它(因为我没有测试)

      PPS:您的第一个问题是“特定日期是否应用了日光?”This answer solves the task

      【讨论】:

        猜你喜欢
        • 2022-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-05
        • 1970-01-01
        • 2017-01-02
        • 1970-01-01
        • 2013-03-16
        相关资源
        最近更新 更多