MomentJS/Date object UTC by default

后端 未结 2 1196
清歌不尽
清歌不尽 2021-01-14 05:06

I am using MomentJS in my angular project and i\'m having a lot of issues with different date timezones.

My app should not take into consideration any timezones, how

2条回答
  •  独厮守ぢ
    2021-01-14 05:15

    You can use moment-timezone with moment.

    And then set default UTC timezone with code below:

    import * as moment from 'moment-timezone';
    ...
    moment.tz.setDefault('Etc/UTC');
    

    A possible option in Angular could be to create a singleton instance LocaleService to manage localization related parameters.

    import { Injectable } from '@angular/core';
    import * as moment from 'moment-timezone';
    
    @Injectable({
      providedIn: 'root'
    })
    export class LocaleService {
    
      constructor() {
        this.setDefaultTimezone();
      }
    
      setDefaultTimezone() {
        moment.tz.setDefault('Etc/UTC');
      }
    
      // other stuff related to localization
      ...setCurrentTimezone()
      ...setLocale()
    }
    

    And then, we need to provide this service via AppModule, and also don't forget to inject it in a global component, for instance AppComponent, in order to be instantiated.

提交回复
热议问题