2009-10-20 35 views
6

以下是一個及時的問題。對於時間的變化在北美*的規則是:JavaScript - 查找下一次更改日期(標準或日光)

  • 第一個星期日十一月,抵消月更改爲標準(-1小時)
  • 第二個星期日,偏移改變日光(您與GMT的正常偏移量)

考慮JavaScript中的一個函數,該函數接受Date參數,並應確定參數是標準還是夏令時。

問題的根源在於:

  • 你會如何構建下一次更改的日期?

算法/僞目前看起來是這樣的:

 
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 firstSunday; 

    if (firstOfMonthDayOfWeek != 0) //Sunday! 
    { 
     //need to find a way to determine which date is the second Sunday 
    } 

} 

的這裏的約束是使用標準的JavaScript函數,而不是刮Date對象的任何JavaScript引擎的解析。此代碼不會在瀏覽器中運行,因此這些不錯的解決方案不適用。

**不是所有的地方/在北美的更換時間的區域。*

回答

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 
} 
0

1)我希望有可能是在不同國家的一些其他規則。有些根本沒有夏令時。因此,要在特定區域設置中找到答案,您可能需要循環365(6)天以查找getTimetoneOffset()更改其值的日期。這不應該是一個很大的表現滯後。 2)然後,當時間變化時(美國凌晨2點),你可以得到特定的小時。建議在24小時內通過另一個環路


PS:Ok,someone has already done the job =)。你應該在使用前測試它(因爲我沒有測試)

PPS:你的第一個問題是「是否適用於特定日期的日光?This answer solves the task