Calculating daylight saving time from only date

后端 未结 9 1755
春和景丽
春和景丽 2021-01-31 10:53

I am working with an Arduino and a real time clock chip. The chip compensates for leap years and such, so it will always have the correct date, but it does not handle daylight s

9条回答
  •  青春惊慌失措
    2021-01-31 11:01

    Here is my answer, and I welcome any corrections. It is assumed that the years are between 2000 and 2099 inclusive. Further details available via the reference link.

      int timezone = 0;  // Set to correct initial value depending on where you are (or via GPS if you like).
      // Calculate day of week for Daylight savings time.
      int day_of_week = (day_of_month + int(2.6 * (((month + 12 - 3) % 12) + 1) - 0.2) - 40 + 
                  (month < 3 ? year-1 : year) + int((month < 3 ? year-1 : year)/4) + 5) % 7;
      // Adjust timezone based on Daylight savings time for northern hemisphere, USA
      if ((month  >  3 && month < 11 ) || 
          (month ==  3 && day_of_month >= 8 && day_of_week == 0 && hour >= 2) ||  // DST starts 2nd Sunday of March;  2am
          (month == 11 && day_of_month <  8 && day_of_week >  0) ||
          (month == 11 && day_of_month <  8 && day_of_week == 0 && hour < 2)) {   // DST ends 1st Sunday of November; 2am
        timezone++;
      }
    

    Day of Week calculation reference: How to determine the day of the week, given the month, day and year
    DST test reference is via this article as answered by captncraig and my own reasoning and interpretation of his answer.

提交回复
热议问题