Time Zones and Servers

  • May 08, 2014 at 9:25 PM
  • Shawn Wildermuth
  • 2 Comments

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?

 


Leave a Comment

*
*
*