Time Zones and Servers

Posted by Shawn Wildermuth on May 08, 2014 on 17:25PM

Wonder-121-Time-Zone-Static-ImageI am getting married and that means I get a bunch of development tasks to do for the wedding planning. I guess it’s my own fault, I did propose with an app.

One of the tasks I had to do was create a new page on my wedding site for the day of the wedding to include things like directions and parking. Pretty simple HTML stuff, but one thing I wanted to be sure of was to only show the page on the day of the wedding. This should be easy, but the time zone of the server has kicked my ass before.

The problem is that if I check for the date, the date might get shifted if the time is after midnight where the server is. Luckily the TimeZoneInfo class makes this pretty easy in C#. The trick is to first get the time zone you care about:

var tz = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");

Once I have the time zone, I can convert the current time to my time zone:

var today = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tz);

Lastly, I can test the date portion of the DateTime to make sure it’s the right date:

if (today.Date == new DateTime(2014, 05,31))
  return RedirectToAction("DayOfWedding");

Easy, right?

Application Name WilderBlog Environment Name Production
Application Ver Runtime Framework .NETCoreApp,Version=v1.1
App Path D:\home\site\wwwroot Runtime Version .NET Core 4.6.24628.01
Operating System Microsoft Windows 6.2.9200 Runtime Arch X86