Creating Time Zone Calculator Using jQuery & Google API

In this post, we will try to create a time zone calculator. We will be calculating the timezone in two ways.

  • Using normal jQuery functions
  • Using Google API

We will be using Visual Studio as our IDE. For jQuery implementation, we will be creating some prototypes. I hope you will like this.

Download Source Code

You can always download the source code from here: Time Zone Calculator

Background

In one of my projects, we were saving some date values in UTC format in the Server. When we returned the data, we were not doing any calculation like converting the same date values to the user's location time. If it is India (UTC – IST), I was asked to get the time zone values from the client side and pass the same value to the Server in each request. I had done this and here, I will show you how. As I explained above, we can do this in two ways.

  • Using normal jQuery functions
  • Using Google API

We will be explaining these two methods one by one.

Using the code

First of all, create a new project in Visual Studio, install jQuery and bootstrap from NuGet package manager. Once your project is ready, we will start implementing our first method.

Using jQuery functions

The first thing you need to do here is adding the needed elements to UI.

  1. <div class="col-sm-6">  
  2.     <h3>Using jQuery prototype function</h3>  
  3.     <p>Here we are going to use prototype functions we created</p>  
  4.     <div class="form-group"> <label class="label label-primary">Please select date:</label> <br /> <br /> <input class="form-control" type="text" id="txtTimeZone" /> <br /> <br /> <input type="button" value="Submit" id="btnSubmit" class="btn btn-primary btn-block" /> <br />  
  5.         <div class="panel panel-default">  
  6.             <div id="placeholder" class="panel-body"></div>  
  7.         </div>  
  8.     </div>  
  9. </div>  
Please add the needed references to your page.
  1. <link href="Content/themes/base/all.css" rel="stylesheet" />  
  2. <link href="Content/bootstrap.min.css" rel="stylesheet" />  
  3. <link href="Content/Index.css" rel="stylesheet" />  
  4. <script src="Scripts/jquery-2.2.3.min.js"></script>  
  5. <script src="Scripts/jquery-ui-1.11.4.min.js"></script>  
Now, we are going to create some date prototypes to a js file TimeZone.js, so that we can use it with any date object.
  1. Date.prototype.dst = function()   
  2. {  
  3.     return this.getTimezoneOffset() < this.stdTimezoneOffset();  
  4. }  
The code given above, is for finding whether the daylight time is on or off. If it returns true it means the daylight time is off.
  1. Date.prototype.stdTimezoneOffset = function()   
  2. {  
  3.     var jan = new Date(this.getFullYear(), 0, 1);  
  4.     var jul = new Date(this.getFullYear(), 6, 1);  
  5.     return (Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset()) * -1);  
  6. }  
The above prototype can be called when the daylight time is OFF.
  1. Date.prototype.stdTimezoneOnset = function ()   
  2. {  
  3. var jan = new Date(this.getFullYear(), 0, 1);  
  4. var jul = new Date(this.getFullYear(), 6, 1);  
  5. return (Math.min(jan.getTimezoneOffset(), jul.getTimezoneOffset()) * -1);  
  6. }  
The prototype given above, can be called when the daylight time is on.

Now, we have created all the prototypes required. Shall we go and use these now?

  1. $(document).ready(function()   
  2. {  
  3.     $("#txtTimeZone").datepicker();  
  4.     $('#btnSubmit').click(function()  
  5.      {  
  6.         var dayLight = new Date();  
  7.         dayLight = new Date($('#txtTimeZone').val());  
  8.         if (dayLight.dst())  
  9.         {  
  10.             timeZoneValue = dayLight.stdTimezoneOffset(); // Day light time is OFF  
  11.         } else  
  12.         {  
  13.             timeZoneValue = dayLight.stdTimezoneOnset(); // Day light time is ON  
  14.         }  
  15.         $("#placeholder").text('The time zone value for ' + dayLight + ' is ' + timeZoneValue);  
  16.     });  
  17. });  
Please run your page now to check the output.

output
Time zone calculation, using jQuery

output
Time zone calculation, using jQuery output

Now, we will implement the second method. Is that fine?

Using Google API

Before we start, please get your own map API key from Google. You can follow this link to get one.

I hope you have your own key now. If yes, you are ready to go. Please add some controls, given below:

  1. <div class="col-sm-6">  
  2.     <h3>Using Google API</h3>  
  3.     <p>Here we are going to use Google API</p>  
  4.     <div class="form-group"> <input id="pac-input" class="controls" type="text" placeholder="Search Box">  
  5.         <div id="map"></div>  
  6.         <script async defer src="https://maps.googleapis.com/maps/api/js?key=yourkey&libraries=places&callback=initAutocomplete" type="text/javascript"></script>  
  7.         <div class="panel panel-default">  
  8.             <div id="latlon" class="panel-body"></div>  
  9.         </div>  
  10.     </div>  
  11. </div>  
Here initAutocomplete is the callback function, which is given below:
  1. function initAutocomplete()  
  2. {  
  3.     var map = new google.maps.Map(document.getElementById('map'),  
  4.      {  
  5.         center:  
  6.         {  
  7.             lat: -33.8688,  
  8.             lng: 151.2195  
  9.         },  
  10.         zoom: 13,  
  11.         mapTypeId: google.maps.MapTypeId.ROADMAP  
  12.     });  
  13.     // Create the search box and link it to the UI element.  
  14.     var input = document.getElementById('pac-input');  
  15.     var searchBox = new google.maps.places.SearchBox(input);  
  16.     map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);  
  17.     // Bias the SearchBox results towards current map's viewport.  
  18.     map.addListener('bounds_changed', function()  
  19.     {  
  20.         searchBox.setBounds(map.getBounds());  
  21.     });  
  22.     var markers = [];  
  23.     // Listen for the event fired when the user selects a prediction and retrieve  
  24.     // more details for that place.  
  25.     searchBox.addListener('places_changed', function()\  
  26.     {  
  27.         var places = searchBox.getPlaces();  
  28.         debugger;  
  29.         if (places.length == 0)  
  30.         {  
  31.             return;  
  32.         }  
  33.         // Clear out the old markers.  
  34.         markers.forEach(function(marker)  
  35.         {  
  36.             marker.setMap(null);  
  37.         });  
  38.         markers = [];  
  39.         // For each place, get the icon, name and location.  
  40.         var bounds = new google.maps.LatLngBounds();  
  41.         places.forEach(function(place)  
  42.          {  
  43.             var icon =   
  44.             {  
  45.                 url: place.icon,  
  46.                 size: new google.maps.Size(71, 71),  
  47.                 origin: new google.maps.Point(0, 0),  
  48.                 anchor: new google.maps.Point(17, 34),  
  49.                 scaledSize: new google.maps.Size(25, 25)  
  50.             };  
  51.             // Create a marker for each place.  
  52.             markers.push(new google.maps.Marker  
  53.             ({  
  54.                 map: map,  
  55.                 icon: icon,  
  56.                 title: place.name,  
  57.                 position: place.geometry.location  
  58.             }));  
  59.             $('#latlon').text(place.geometry.location.lat() + ',' + place.geometry.location.lng() + ', The time zone value is ' + place.utc_offset);  
  60.             if (place.geometry.viewport)  
  61.             {  
  62.                 // Only geocodes have viewport.  
  63.                 bounds.union(place.geometry.viewport);  
  64.             } else {  
  65.                 bounds.extend(place.geometry.location);  
  66.             }  
  67.         });  
  68.         map.fitBounds(bounds);  
  69.     });  
  70. }  
Following is the custom code we have written to show the timezone values to our text box.
  1. $('#latlon').text(place.geometry.location.lat() + ',' + place.geometry.location.lng() + ', The time zone value is ' + place.utc_offset);  
Now, it is time to add our styles.
  1. #map {  
  2.     width100 % ;  
  3.     height200 px;  
  4.     background - color#CCC;  
  5. }.controls {  
  6.     margin - top: 10 px;  
  7.     border1 px solid transparent;  
  8.     border - radius: 2 px 0 0 2 px;  
  9.     box - sizing: border - box; - moz - box - sizing: border - box;  
  10.     height32 px;  
  11.     outlinenone;  
  12.     box - shadow: 0 2 px 6 px rgba(0000.3);  
  13. }#pac - input {  
  14.     background - color#fff;  
  15.     font - family: Roboto;  
  16.     font - size15 px;  
  17.     font - weight: 300;  
  18.     margin - left: 12 px;  
  19.     padding0 11 px 0 13 px;  
  20.     text - overflow: ellipsis;  
  21.     width300 px;  
  22. }#pac - input: focus {  
  23.         border - color#4d90fe;  
  24. }  
  25. .pac-container {  
  26. font-family: Roboto;  
  27. }  
  28. #type - selector {  
  29.                 color#fff;  
  30.                 background - color#4d90fe;  
  31. padding5px 11px 0px 11px;  
  32. }  
  33. #type - selector label {  
  34.                     font - family: Roboto;  
  35.                     font - size13 px;  
  36.                     font - weight: 300;  
  37.                 }#target {  
  38.                     width345 px;  
  39.                 } 
Please note that  if you don’t set the height for the map container div, the map may not be loaded. Hence,
 I have given the CSS for my map container as follows:
  1. #map {  
  2. width100%;  
  3. height200px;  
  4. background-color#CCC;  
  5. }  
Now, please run your page. You can see a map in your page. Please search for any location, it will give you the timezone value for the given location. Shall we check?

output

Time zone calculation, using Google API

Please make sure that the value you get from both methods is the same.

output

Time zone calculation

That’s all -- happy coding!.

Conclusion

Did I miss anything that you may think is required? Did you find this post useful? I hope,you liked this article. Please share with me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without the comments, but try to stay on the topic. If you have a question unrelated to this post, you’re better off, posting it on C# Corner, Code Project, Stack Overflow, ASP.NET Forum instead of commenting here. Tweet or Email me a link to your question there and I’ll definitely try to help, if I can.

Please see this article in my blog here.


Similar Articles