Welcome to CSharp Labs

JavaScript TimeZone Detection with MVC 4

Thursday, May 16, 2013

Updated December 30, 2014: Fixed dst detection bugs.

The DynamicWebTimeZone class generates a small (<5KB) JavaScript time zone detecting snippet that determines the user's time zone.

Do to the nature of time zones and fluctuating day light saving times, the JavaScript detector code is dynamically created and cached by reading TimeZoneInfo.GetSystemTimeZones().

Usage: Requires WebGrease for JavaScript optimization, included with new MVC 4 projects.

Create a new controller with an action that returns the script:

        private static DynamicWebTimeZone _Detector = new DynamicWebTimeZone();

        //TODO: Emit E-TAG
        [OutputCache(Duration = 600)]
        public ActionResult TimeZoneDetector()
        {
            return Content(_Detector.TimeZoneDetectorJavascript, "application/x-javascript");
        }

Add an action that returns a partial view and the object DynamicWebTimeZone.GetTimeZones returns as a model:

        [ChildActionOnly]
        [OutputCache(Duration = 600)]
        public ActionResult TimeZoneSelect()
        {
            return PartialView("_TimeZoneSelectPartial", _Detector.GetTimeZones());
        }

 Create a new partial view that populates a drop down list with the model and name it _TimeZoneSelectPartial:

@model  IEnumerable<System.Web.Util.DynamicWebTimeZone.TimeZoneIdentifier>

@Html.DropDownList("UserTimeZone", Model.Select(e => new SelectListItem { Text = e.DisplayName, Value = e.ID }))

The SystemWorks.TimeZone.determine_timezone() returns an object with time zone information:

  • success (boolean) : determines if the time zone was detected
  • name (string) : the time zone identifier
  • dst (boolean) : determines if the time zone observes day light savings time
  • offset (string) : the time zone offset

When you are ready to display the time zone drop down list, include the following in a view:

@Html.Action("TimeZoneSelect", "DynamicJava")

<script type="text/javascript" src="/DynamicJava/TimeZoneDetector"></script>

<script type="text/javascript">
    (function (SystemWorks) {
        var zone = SystemWorks.TimeZone.determine_timezone();
        if (zone.success())
            window.document.getElementById('UserTimeZone').value = zone.name();
    }(window.SystemWorks = window.SystemWorks || {}));
</script>

Download DynamicWebTimeZone Class

Comments