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.

I should clarify that the value given by dateObject.getTimezoneOffset() is the value added to the local time to get the corresponding value in GMT.  I've made the mistake of using the value to calculate the local time by simply adding to the current GMT value.  Need to remember to negate the value (multiply by -1) to go from GMT to the local time.

About these ads

Actions

Information

3 responses

2 07 2014
4 07 2014
6 07 2014

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




Follow

Get every new post delivered to your Inbox.

Join 392 other followers

%d bloggers like this: