DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more

Time Zone Calculator

Check out this nifty time zone calculator demonstrated using jQuery and a Google API.

Sibeesh Venu user avatar by
Sibeesh Venu
·
Jun. 30, 16 · Tutorial
Like (10)
Save
Tweet
Share
5.03K Views

Join the DZone community and get the full member experience.

Join For Free

in this post, we will try to create a time zone calculator. we will be calculating time zones in two ways:

  • using normal jquery functions
  • using the google api
  • we will be using visual studio as our ide. for the jquery implementation, we will be creating some prototypes.

    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 on the server. when we returned the data we were not doing any calculation like converting the date values to user location time—if it is india utc – ist. therefore 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 and 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.

    <div class="col-sm-6">
                 <h3>using jquery prototype function</h3>
                 <p>here we are going to use prototype functions we created</p>
                 <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 />
                     <div class="panel panel-default">
                         <div id="placeholder" class="panel-body"></div>
                     </div>
                 </div>
             </div>

    please add the needed references to your page.

    <link href="content/themes/base/all.css" rel="stylesheet" />
    <link href="content/bootstrap.min.css" rel="stylesheet" />
        <link href="content/index.css" rel="stylesheet" />
        <script src="scripts/jquery-2.2.3.min.js"></script>
        <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 objects.

    date.prototype.dst = function () {
        return this.gettimezoneoffset() < this.stdtimezoneoffset();
    }

    the above code is for finding whether daylight time is on or off if it returns true it means that daylight time is off.

    date.prototype.stdtimezoneoffset = function () {
        var jan = new date(this.getfullyear(), 0, 1);
        var jul = new date(this.getfullyear(), 6, 1);
        return (math.max(jan.gettimezoneoffset(), jul.gettimezoneoffset()) * -1);
    }

    the above prototype can be called when the daylight time is off.

    date.prototype.stdtimezoneonset = function () {
        var jan = new date(this.getfullyear(), 0, 1);
        var jul = new date(this.getfullyear(), 6, 1);
        return (math.min(jan.gettimezoneoffset(), jul.gettimezoneoffset()) * -1);
    }

    the above prototype can be called when the daylight time is on.

    now we have created all the prototypes needed. we can use them now.

    $(document).ready(function () {
        $("#txttimezone").datepicker();
        $('#btnsubmit').click(function () {
            var daylight = new date(); 
            daylight = new date($('#txttimezone').val());
            if (daylight.dst()) {
                timezonevalue = daylight.stdtimezoneoffset();// day light time is off
            } else {
                timezonevalue = daylight.stdtimezoneonset();// day light time is on
            }
            $("#placeholder").text('the time zone value for ' + daylight + ' is ' + timezonevalue);
        });
    });

    please run your page now to check the output.


    image title


    using google api

    before we start, please get your own map api key from google. you can follow this link to get one.

    please add some controls as below to your page.

    <div class="col-sm-6">
                    <h3>using google api</h3>
                    <p>here we are going to use google api</p>
                    <div class="form-group">
                        <input id="pac-input" class="controls" type="text" placeholder="search box">
                        <div id="map"></div>
                        <script async defer src="https://maps.googleapis.com/maps/api/js?key=yourkey&libraries=places&callback=initautocomplete" type="text/javascript"></script>
                        <div class="panel panel-default">
                            <div id="latlon" class="panel-body"></div>
                        </div>
                    </div>
                </div>

    here initautocomplete is the callback function which we are going to write now.

    function initautocomplete() {
        var map = new google.maps.map(document.getelementbyid('map'), {
            center: { lat: -33.8688, lng: 151.2195 },
            zoom: 13,
            maptypeid: google.maps.maptypeid.roadmap
        });
        // create the search box and link it to the ui element.
        var input = document.getelementbyid('pac-input');
        var searchbox = new google.maps.places.searchbox(input);
        map.controls[google.maps.controlposition.top_left].push(input);
        // bias the searchbox results towards current map's viewport.
        map.addlistener('bounds_changed', function () {
            searchbox.setbounds(map.getbounds());
        });
        var markers = [];
        // listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchbox.addlistener('places_changed', function () {
            var places = searchbox.getplaces();
            debugger;
            if (places.length == 0) {
                return;
            }
    
            // clear out the old markers.
            markers.foreach(function (marker) {
                marker.setmap(null);
            });
            markers = [];
    
            // for each place, get the icon, name and location.
            var bounds = new google.maps.latlngbounds();
            places.foreach(function (place) {
                var icon = {
                    url: place.icon,
                    size: new google.maps.size(71, 71),
                    origin: new google.maps.point(0, 0),
                    anchor: new google.maps.point(17, 34),
                    scaledsize: new google.maps.size(25, 25)
                };
    
                // create a marker for each place.
                markers.push(new google.maps.marker({
                    map: map,
                    icon: icon,
                    title: place.name,
                    position: place.geometry.location
                }));
                $('#latlon').text(place.geometry.location.lat() + ',' + place.geometry.location.lng() + ', the time zone value is ' + place.utc_offset);
                if (place.geometry.viewport) {
                    // only geocodes have viewport.
                    bounds.union(place.geometry.viewport);
                } else {
                    bounds.extend(place.geometry.location);
                }
            });
            map.fitbounds(bounds);
        });
    }

    next is the custom code we have written for showing the time zone values to our text box.

    $('#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.

    #map {
        width: 100%;
        height: 200px;
        background-color: #ccc;
    }
    
    .controls {
        margin-top: 10px;
        border: 1px solid transparent;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        height: 32px;
        outline: none;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
    }
    
    #pac-input {
        background-color: #fff;
        font-family: roboto;
        font-size: 15px;
        font-weight: 300;
        margin-left: 12px;
        padding: 0 11px 0 13px;
        text-overflow: ellipsis;
        width: 300px;
    }
    
        #pac-input:focus {
            border-color: #4d90fe;
        }
    
    .pac-container {
        font-family: roboto;
    }
    
    #type-selector {
        color: #fff;
        background-color: #4d90fe;
        padding: 5px 11px 0px 11px;
    }
    
        #type-selector label {
            font-family: roboto;
            font-size: 13px;
            font-weight: 300;
        }
    
    #target {
        width: 345px;
    }

    please note that if you don’t set height for the map container div, the map may not get loaded. i have given the css for my map container as follows.

    #map {
        width: 100%;
        height: 200px;
        background-color: #ccc;
    }

    now, please run your page and you should see a map. search for any location, and it will give you the timezone value for the chosen location.

    image title

    image title


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

    conclusion

    did i miss anything? please share any suggestions and feedback you might have.

    Calculator (Mac OS)

    Published at DZone with permission of Sibeesh Venu, DZone MVB. See the original article here.

    Opinions expressed by DZone contributors are their own.

    Popular on DZone

    • DZone's Article Submission Guidelines
    • OWASP Kubernetes Top 10
    • Create a REST API in C# Using ChatGPT
    • When to Choose Redpanda Instead of Apache Kafka

    Comments

    Partner Resources

    X

    ABOUT US

    • About DZone
    • Send feedback
    • Careers
    • Sitemap

    ADVERTISE

    • Advertise with DZone

    CONTRIBUTE ON DZONE

    • Article Submission Guidelines
    • Become a Contributor
    • Visit the Writers' Zone

    LEGAL

    • Terms of Service
    • Privacy Policy

    CONTACT US

    • 600 Park Offices Drive
    • Suite 300
    • Durham, NC 27709
    • support@dzone.com
    • +1 (919) 678-0300

    Let's be friends: