Why doesn't subtracting two local DateTime values appear to account for Daylight Saving Time?

前端 未结 3 1204
感情败类
感情败类 2021-01-06 05:12

I\'m playing with some C# code to try to gain an understanding of how subtracting DateTime objects in C# works with respect to Daylight Saving Time.

Per Google and o

3条回答
  •  天命终不由人
    2021-01-06 05:59

    Ok, so I made some minor changes to your code. Not sure if this is what you are trying to achieve or not but this will give you what you want...

    static void Main() {
            TimeZoneInfo easternStandardTime = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
            TimeZone timeZone = TimeZone.CurrentTimeZone;
    
            DateTime oneAm = TimeZoneInfo.ConvertTime(new DateTime(2017, 03, 12, 01, 00, 00), easternStandardTime);
            DateTime fourAm = TimeZoneInfo.ConvertTime(new DateTime(2017, 03, 12, 04, 00, 00), easternStandardTime);
    
            DaylightTime time = timeZone.GetDaylightChanges(fourAm.Year);
    
            TimeSpan difference = ((fourAm - time.Delta) - oneAm);
    
            Console.WriteLine(oneAm);
            Console.WriteLine(fourAm);
            Console.WriteLine(TimeZoneInfo.Local.IsDaylightSavingTime(oneAm));
            Console.WriteLine(TimeZoneInfo.Local.IsDaylightSavingTime(fourAm));
            Console.WriteLine(difference);
            Console.ReadLine();
        }
    

提交回复
热议问题