Monday, 25 February 2013

how to get current user time zone in C#

how to get current user time zone in DropdownList

1) Add DropDownList to Page
2) Get All Time Zone and UTC offsets for each Time Zone
     and then Populate DropDownList

        void PopulateDropDown()
            System.Collections.ObjectModel.ReadOnlyCollection<TimeZoneInfo> tzinfo =
            foreach (TimeZoneInfo tz in tzinfo)
                ListItem item = null;
                TimeSpan ts=tz.GetUtcOffset(DateTime.Now);

                item = new ListItem(tz.Id + ": " +
3) Once DropDownlist is populated at server side. Now We need to find User's TimeZone using Javascript

using JavaScript Date class, you can find out current DateTime and TimeZone Info.
  var d=new Date();
   var usersTime = d.toString();  

4) Here is the Javascript Code to match User's Current TimeZone in DropDownList.

   d.toString()   for IE 9  returns in UTC format(i.e Mon Feb 25 23:03:42 UTC+0530 2013)
   d.toString()  for  Firefox 19.0 returns in GMT format(i.e Mon Feb 25 2013 23:04:13 GMT+0530 (India Standard Time))

 Gets Time Zone Offset  i.e +0530  and compares this value with list of Zones available in DropDown List

Here is the Complete Scrip Code

    <script type="text/javascript">
        function SelectCurrentTimeZone() {
            var d = new Date();
            if (d.toString().search(new RegExp("UTC", "ig")) >= 0)
                timeOffset = d.toString().split("UTC");
            else timeOffset = d.toString().split("GMT");

            var timezone = timeOffset[1].split(' ')[0];
            var comp = timezone.substr(0, 3) + ":" + timezone.substr(3) + ":" + "00";
            comp=comp.replace("+", "");

            var sel = document.getElementById('DropDownList1');
            var b = false;
            for (i = 0; i < sel.options.length; i++) {
                if (sel.options[i].value == comp) {
                    document.writeln(sel.options[i].selected + "<br>");
                    sel.selectedIndex = i;
                     //you can remove this coloring
                      sel.options[i].style.color = "red";

b = true;
Note: Add this script before the closing body  tag(</body>).

5) Run the WebPage

Here is the Output

how to get current user time zone in using javascript

Tags:how to get current user time zone in,how to get current user time zone in DropdownList,DropDownList with Current User Time Zone example(using JavaScript),how to get current user time zone in C#