WaltiD
WaltiD

Reputation: 1952

How to simulate daylight saving time transition in a unit test?

I have a code, that compare the last timestamp with the actual timestamp. If the actual timestamp is before the last timestamp, the systemtime has been manipulated. Because of the transition from or to daylight saving time, I work with UTC.
Now I would like to write an unit test for this special 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 define that a 02.18 am is either DST or not.

Upvotes: 11

Views: 7313

Answers (2)

Matthew Whited
Matthew Whited

Reputation: 22443

If you are trying to tset static methods or properties you could look at PEX/Moles

Upvotes: -2

Archie
Archie

Reputation: 66

MSDN says:

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

IMO you should add your minutes in UTC and then convert to local kind.

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 code above prints 02:58 before and after DST shift.

Upvotes: 5

Related Questions