1

I would like to be able to change the date for a .NET process from within that process whilst it is running. I am not sure if this is even possible. Let's assume W7 or greater, 32 and 64bit. From within the process, when I call something like DateTime.Today, i would like it to report the date of my choosing. I am not too concerned about changing the time, i would like the time of day to remain unchanged at the moment.

As far as I can tell this is not a duplicate question,I have seen posts such as change-system-date-programatically that make a call to SetSystemTime but this changes the datetime for the whole machine, I would like to change it just for that process.

I have been using NirSoft RunAsDate which uses an application to call the .net executable and this works fine, I would just like to be able to control this myself from within the application. The fact that this tool can make the change suggests that it is possible.

The background is that I am testing some functionality which behaves differently depending on the current date and i need to able to simulate this at any given time and make the application behave as if it was running on a given date. I dont want to alter teh system clock as this may have unintended consequences for other applications that are running

(first post - go easy on me)

Community
  • 1
  • 1
thehill
  • 93
  • 11
  • 2
    As I know you can't change date for process itself. Just for the whole system. You can try to hook system call for WinAPI GetSystemTime, but it won't be easy. As another solution you can try to use Microsoft Fakes - http://msdn.microsoft.com/en-us/library/hh549175.aspx, but they are needed for unit testing – Sergey Litvinov Jul 15 '14 at 09:38
  • [See if this helps](http://stackoverflow.com/a/23981327/2530848) – Sriram Sakthivel Jul 15 '14 at 09:57

1 Answers1

3

Implement a factory to supply you with the current DateTime. Have this apply a specified offset to all dates it provides. Everywhere you need a date call this instead of DateTime.UtcNow e.g.

public sealed class DateTimeFactory
{
    private readonly TimeSpan offset;

    public DateTimeFactory(TimeSpan offset)
    {
        this.offset = offset;
    }

    public DateTime UtcNow
    {
        get { return DateTime.UtcNow + offset; }
    }
}
Ananke
  • 1,250
  • 9
  • 11
  • Ananke - i think I was looking for something that would prevent me from having to change every call to DateTime, but after some basic investigation it would seem that Sergey is probably right that hooking GetSystemTime will not be easy. I will vote your solution now, thanks – thehill Jul 15 '14 at 14:15