Ariel Deil
Ariel Deil

Reputation: 108

Using different time than local machine

I have a C# app that is running on windows server. But the time of that server is incorrect (timezone is fine).

How can I force my C# process to sync itself to a time server in a way that the DateTime.Now will return real time but without changing local machine time.

I cannot change all the 'DateTime.Now' uses in my code because there are too many. In adddition, there are external .net DLLs that need to use the same DateTime value.

Upvotes: 1

Views: 314

Answers (1)

CodeCaster
CodeCaster

Reputation: 151720

How can I force my C# process to sync itself to a time server in a way that the DateTime.Now will return real time but without changing local machine time.

You can't:

DateTime.Now Property

Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time.

Internally, on Windows, this calls the GetSystemTimeAsFileTime() or GetSystemTimePreciseAsFileTime() function. In other words, you can't trivially circumvent DateTime.Now returning the machine's time.

Sure, using detours or Moles (superseded by Fakes in VS2012 and IntelliTest in VS2015 [Enterprise license required], but see the VS 2008/2010 downloads) you can re-route those Windows API or .NET API calls, but you generally don't want to.

Instead ask the server owner to set up proper time synchronization using NTP.

Upvotes: 1

Related Questions