JavaScript – Get Local Timezone of Client

The post shows you how to get local timezone of a client, who is visiting your website.

To do this, we get the timeZone value that is returned by Intl.DateTimeFormat.prototype.resolvedOptions() method. But this approach does not work in IE browser. In order to solve this problem, we need to use a 3rd party timezone library, such as JSTZ, Moment.js, etc. In this post, we show you how to combine Intl with JSTZ library.

 

1. Implementation

Let’s create a js file and add the following function.

local-timezone.js
function getClientLocalTimezone() {
    var localTimezone = null;
    
    if (typeof Intl !== 'undefined') {
        // use Intl approach
        localTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    }
    
    if (!localTimezone) {
        // use jstz approach in IE browser
        localTimezone = jstz.determine().name();
    }

    return localTimezone;
}

 

2. Example

Create an example.html file and include JSTZ library and add our getClientLocalTimezone() function. Click on the “Run Example” to see how it works.

example.htmlRun Example
<!DOCTYPE html>
<html>
<head>
    <title>JavaScript – Get Local Timezone of Client | ByteNota</title>
</head>
<body>
    <h3>Your Local Timezone:</h3>
    <p id="result"></p>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.min.js"></script>

    <script type="text/javascript">
    
        function getClientLocalTimezone() {
            var localTimezone = null;
            
            if (typeof Intl !== 'undefined') {
                // use Intl approach
                localTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
            }
            
            if (!localTimezone) {
                // use jstz approach in IE browser
                localTimezone = jstz.determine().name();
            }

            return localTimezone;
        }


        var localTimezone = getClientLocalTimezone();
        document.getElementById('result').innerHTML = localTimezone;

    </script>

</body>
</html>

Leave a Reply

avatar