Monday, 25 February 2013

how to get current user time zone in DropdownList VB.NET

how to get current user time zone in DropdownList VB.NET

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

        Private  Sub PopulateDropDown()

            System.Collections.ObjectModel.ReadOnlyCollection<TimeZoneInfo> tzinfo =
            Dim tz As TimeZoneInfo
            For Each tz In tzinfo
                Dim item As ListItem =  Nothing

                Dim ts As TimeSpan = tz.GetUtcOffset(DateTime.Now)

                item = New ListItem(tz.Id ": "
                    " " ts.ToString()),

End Sub

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 VB.NET

No comments:

Post a Comment