Getting the client UTC Offset with ASP.NET

21 09 2007

I have a database where date and time are stored in GMT/UTC to have a uniform time zone reference.  The problem is that it isn’t very user friendly to display the GMT/UTC values.  In addition, we wanted to get the offset without having the user log in and get preference settings.

 Our approach was to get the client offset with JavaScript and added a function that is fired when the page is loaded.


<script>
function GetClientUtcOffset()
{
    var d = new Date();
    document.forms[0]["UtcOffset"].value
        = d.getTimezoneOffset();
}
</script>

Note that the method getTimezoneOffset() returns the unit value in minutes.  Within the body of the page we call the function during the onload event of the body and used a hidden field for the UTC Offset value that we’ll be getting that we’ll be accessing in our code behind.

<body onload="GetClientUtcOffset();">
  <form id="form1" runat="server">
      <input type="hidden" runat="server" id="UtcOffset" />
  .
  .
  .

In our code behind, we got the value and put it in a cookie. The alternative was to put it in a session.


protected void Page_Load(object sender, EventArgs e)
{
  if (IsPostBack && Request.Cookies["utcOffset"] == null)
  {
      HttpCookie utcOffsetCookie =
        new HttpCookie("utcOffset", "0");
      if (!string.IsNullOrEmpty(UtcOffset.Value))
          utcOffsetCookie.Value = UtcOffset.Value;
      Response.Cookies.Add(utcOffsetCookie);
  }
}

At this point, you can retrieve the cookie from any other page and adjust your time values accordingly. Only caveat to this is that the client must hit the page first and then send a post back to get the value of their offset. In our case, we added the code on our login page since we didn’t allow annonymous access to the site.

Read the rest of this entry »