简体   繁体   中英

Enforce timezone for angular.js application

I'd like to use one single timezone for an angular.js application. I'm aware that angular.js currently uses browsers timezone settings for date formatting, but I'd like to override this setting so that I can enforce a specific timezone for a user so that it doesn't depend on a browser settings.

It is a business application in question so there is no need for user specific timezones. Everything happens in a company's specified timezone and this is why I'd like to enforce it for every user. Data is saved in UTC, but it needs to be shown in company timezone for every user without depending on user location/locale/browser settings.

Is there any way I can accomplish this that anyone is aware of? And if there is, it'd be greatly appreciated to point me to correct way to do it :) So far I've had zero luck with it.

You can use a library such as timezone.js , or moment.js . I've used timezone successfully, and I've heard moment.js works pretty well. You'll likely want to make an injectable factory..

angular.module('date', [])
.config(function () {
    timezoneJS.timezone.zoneFileBasePath = '/tz';
    timezoneJS.timezone.init();
})
.service('dateConverter', function () {
    return {
        toDisplayDate: function (utcDateIn) {
            return new timezoneJS.Date(utcDateIn, 'America/Los_Angeles')
        }
    }
});

That's just off the top of my head, but it's an example of what you'll probably have to do - convert dates from native JS to the library dates.

Sorry, but it's not possible to change the time zone behavior of the JavaScript Date object. It will always use the time zone of the computer that it's running on.

The best you can do is work around it with one of the libraries listed here . Stephen's answer shows how you can integrate one of them in to Angular.

Also, I'd consider very carefully when you say "there is no need for user specific timezones". Sometimes, that is the case, but very rarely. Often, companies have locations in multiple time zones, or they have employees that travel, or they interact with customers or partners that are in different time zones.

Besides, if what you say is true - that users are always in the single time zone of the company, then wouldn't that already be the local time zone for their computer? If so, then there's not much to do.

If you have users in other time zones, but you wish them to use the company's primary time zone, then that would be a case that would require one of these libraries. But consider carefully the impact of that. Depending on how far away a user is, even their current date might be different than the company's date.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM