Get Timezone from browser using Angularjs

Asked

Viewed 491 times

1

I need to get the user’s browser Timezone. As this is an application using Angularjs, I decided to use the angular-Moment However I did not succeed in getting the name of Timezone.

What I need is a way in Angularjs to get something like : 'America/Sao_paulo', 'Europa/Paris'

I thought about using the library Moment-Timezone.js but I could not add it as dependency in the angular, to use in the controller.

  • In addition to Moment you will need the Timezone Moment for this. http://momentjs.com/timezone/docs/#/using-timezones/guessing-user-Timezone/

2 answers

1

I was able to solve it this way:

I added the lib JSTZ

<script src="js/jstz.min.js"></script>

In the file the controler includes the following code:

/* jstz*/

(function () {
    'use strict';

....

})();

By adding JSTZ at the beginning of the file, I was able to gain access to library functions. So within the controller I executed the following excerpt:

var timezone = jstz.determine();
 console.log(timezone.name()); 

Whose output was : "America/Sao_paulo"

-1

If you want the Browser Timezone formatted you can count on the Javascript method (since Angularjs is just a framework to work with it) Date.toString and do:

var split = new Date().toString().split(" ");
var timeZoneFormatted = split[split.length - 2] + " " + split[split.length - 1];

This will return you "GMT-0400 (EST)" for example, including the time zone minutes when applicable.

Alternatively, with regex you can extract any desired part:

For "GMT-0300 (EDT)" :

new Date().toString().match(/([A-Z]+[\+-][0-9]+.*)/)[1]

To "GMT-0300" :

new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1]

Only "EDT" :

new Date().toString().match(/\(([A-Za-z\s].*)\)/)[1]

Only "-0300":

new Date().toString().match(/([-\+][0-9]+)\s/)[1]
Date.toString reference: 

Reference of Date.toString:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/toString

Browser other questions tagged

You are not signed in. Login or sign up in order to post.