how should i create my own 'now' / DateTime.Now ?
Posted
by Michel
on Stack Overflow
See other posts from Stack Overflow
or by Michel
Published on 2010-06-02T09:02:24Z
Indexed on
2010/06/02
9:13 UTC
Read the original article
Hit count: 206
c#
|best-practices
Hi all,
i'm starting to build a part of a system which will hold a lot of DateTime validations, and a lot of 'if it was done before now' or 'if it will start in an hour etc'.
Usual way to go is to use DateTime.Now to get the actual time.
I predict however, that during unit test that will give me a real headache because i will have to setup my testdata for the time when the test will run in stead of use a default set of test data. So i thought: why not use my own 'now' so i can set the current datetime to any moment in time. As i don't want to set the testservers internal clock i was thinking about this solution, and i was wondering what you think of it. Base thought is that i use my own DateTime class. That class gives you the current datetime, but you can also set your own time from outside.
public static class MyDateTime
{
private static TimeSpan _TimeDifference = TimeSpan.Zero;
public static DateTime Now
{
get
{
return DateTime.Now + _TimeDifference;
}
}
public static void SetNewNow(DateTime newNow)
{
_TimeDifference = newNow - DateTime.Now;
}
public static void AddToRealTime(TimeSpan timeSpan )
{
_TimeDifference = timeSpan;
}
public static void SubtractFromRealTime(TimeSpan timeSpan)
{
_TimeDifference = - timeSpan;
}
}
© Stack Overflow or respective owner