Calculating daylight saving time from only date

后端 未结 9 1596
春和景丽
春和景丽 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

    Code for Central Europe (tested for every day in range 2014-3000 year)

        public static bool IsDst(int day, int month, int dow)
        {
            if (month < 3 || month > 10)  return false; 
            if (month > 3 && month < 10)  return true; 
    
            int previousSunday = day - dow;
    
            if (month == 3) return previousSunday >= 25;
            if (month == 10) return previousSunday < 25;
    
            return false; // this line never gonna happend
        }
    

    Test function

        static void Main(string[] args)
        {
            TimeZoneInfo tzf2 = TimeZoneInfo.FindSystemTimeZoneById("Central Europe Standard Time");
    
            var date = new DateTime(2014, 01, 1, 5, 0,0);
            bool wasSummer = false;
    
            while (date <= new DateTime(3000,1,1))
            {                                         
                var dow = (int) date.DayOfWeek;
    
                var isDst = IsDst(date.Day, date.Month, dow);               
    
                DateTime f2 = TimeZoneInfo.ConvertTime(date, tzf2);
                var isSummer = f2.IsDaylightSavingTime();
    
                if (isSummer != isDst)
                {
                    Console.WriteLine("ERROR");
                    Console.WriteLine(date);
                }
    
                if (isSummer != wasSummer)
                {
                    Console.WriteLine(date.AddDays(-1).ToShortDateString());
                }
    
                date = date.AddDays(1);
                wasSummer = isSummer;
            }
    
            Console.ReadKey();
    

    }

提交回复
热议问题