C# – Uniform Time

Issue

The move to working remotely has presented some for application developers. Desktop applications likely get the current date and time from the host computer. This works great when everyone is in the same office. However, when the application is ran on a computer in another time zone or a Citrix session which sets it’s time to that of the remote computer; spurious errors or chronological anomalies in timestamps can occur.

Solution

A simple solution is to ask the database for the current time.

My app is written in C# .Net and uses LINQ to SQL Server. My steps to implement this are:

  1. Create a global property which queries SQL Server for system time.
  2. Replace all calls to DateTime.Now with SqlServerTime
  3. Replace all calls to DateTime.Today with SqlServerTime.Date

// Returns the time from SQL server.
public static DateTime SqlServerTime
{
    get
    {
        return (new MyRepository.MyRepository()).Database.SqlQuery<DateTime>(@"SELECT SYSDATETIME()").First();                
    }
}

Conclusion

With this easy modification, your date/time sensitive application can be ready for use by remote users around the globe without all the complications of timezone calculations.