Localizing UTC DateTime values from Javascript

by Scosby Monday, July 5, 2010

I had a bunch of <td> tags with a DateTime value for the innerText. Based on convention, the data store keeps this value in UTC time. I wanted to post a bit of javascript that translated the innerText to the client's current time zone. I placed this snippet in my aspx page's head section. I used an ASP.NET GridView to render the data and for the ItemTemplate I simply used an Eval expression to write the time to the <td>.

This is just a short and sweet snippet for my reference, the script certainly could be cleaned up a bit but the intent should be clear enough.

    <script type="text/javascript">

        if (window.addEventListener) {

            window.addEventListener("load", AdjustTimes, false);

        }

        else if (window.attachEvent) {

            window.attachEvent("onload", AdjustTimes);

        }

        else {

            window.onload = AdjustTimes;

        }

        function AdjustTimes()

        {

            var dates = document.getElementsByTagName("td");

            for (var i = 0; i < dates.length; i++) {

                var date = dates[i];

                var dt = new Date(date.innerText);

                if (isNaN(dt)) { continue; }

                else { date.innerText = GetLocalTime(dt); }

            }

        }

        function GetLocalTime(dateValue)

        {

            var d = new Date(dateValue);

            var offset = d.getTimezoneOffset() / 60;

            var nd = new Date(d.getTime() - (3600000 * offset));

            var text = nd.toLocaleString();

            return text;

        }

    </script>

Notice the first thing the script block does is to wire up to the window's load event, this is cross-browser compliant.

Next, we loop through all the <td> tags on the page and translate them to local time if appropriate.

Have fun!

Tags:

blog comments powered by Disqus