How to simulate daylight saving time in unit test?

I have a code that compares the last timestamp with the actual timestamp. If the actual timestamp is up to the last timestamp, control the system’s time. Due to the transition from or to daylight saving time, I work with UTC.
Now I would like to write unit test for this particular situation.

public void TransitionFromDSTToNonDST() { var dayLightChangeEnd= TimeZone.CurrentTimeZone.GetDaylightChanges(DateTime.Now.Year).End; var stillInDaylightSavingTime= dayLightChangeEnd.Subtract(TimeSpan.FromMinutes(62)); //stillInDaylightSavingTime.IsDaylightSavingTime() returns true //stillInDaylightSavingTime is 01.58 am var noDaylightSavingTimeAnymore= dayLightChangeEnd.Subtract(TimeSpan.FromMinutes(32)); //noDaylightSavingTimeAnymore.IsDaylightSavingTime() returns false //noDaylightSavingTimeAnymore is 02.28 am } 

But actually I would like to simulate the following:

 var stillInDaylightSavingTime = //for example 02.18 am BEFORE switching to Non-DST var noDaylightSavingTimeAnymore = //for example 02.10 am AFTER switching to Non-DST 

So, the question is, how can I determine if 02.18 AM is either DST or not.

+8
c # unit-testing mstest
source share
2 answers

MSDN says :

Conversion operations between time zones (for example, between UTC and local time, or between one time zone and another) take into account daylight saving time, but arithmetic and comparison operations are not .

IMO you have to add your minutes in UTC and then convert to local view.

Here's the (updated) code:

 var dayLightChangeEnd = TimeZone.CurrentTimeZone.GetDaylightChanges(DateTime.Now.Year).End.ToUniversalTime(); var stillInDaylightSavingTime = dayLightChangeEnd.Subtract(TimeSpan.FromMinutes(62)).ToLocalTime(); Console.WriteLine(stillInDaylightSavingTime); Console.WriteLine(stillInDaylightSavingTime.IsDaylightSavingTime()); var noDaylightSavingTimeAnymore = dayLightChangeEnd.Subtract(TimeSpan.FromMinutes(2)).ToLocalTime(); Console.WriteLine(noDaylightSavingTimeAnymore); Console.WriteLine(noDaylightSavingTimeAnymore.IsDaylightSavingTime()); 

@WaltiD: I can’t comment, but the above fingerprint code is 02:58 before and after changing DST.

+4
source share

If you are trying to set up static methods or properties, you can look at PEX / Moles

0
source share

All Articles