Search code examples
angulartypescriptangular2-highcharts

Get the timezone from my browser/server to inject in angular2-highcharts


I actually get the timezone setup manually using the timezoneOffset function coming from the Highcharts API, I am currently in gmt+2 so I set it to -2 * 60 but when we go change the hour in October my setup will not work properly anymore, so I decided to take my browser or the server time instead. I know we could take the gettimezoneOffset function coming from the API getTimezoneOffset: Function. The pb is I am setup with typescript and Angular 4, how could I make it in an elegant way? thanks in advance

Here's my actual working code using timezoneOffset:

 constructor(public userService3: UserService3) {

     const Highcharts = require('highcharts');

    Highcharts.setOptions({
  global: {
    timezoneOffset: -2 * 60
   }
});
           this.options = {
            title : { text : '' },
            chart: {  type: 'area'},
            legend: { enabled: false },
            credits: { enabled: false },
            xAxis: { type: 'datetime',
                    startOnTick: false,
                    endOnTick: false,
                    tickInterval: 36e5 * 2, // two hours
                    },
            yAxis: { min: 0,
              max: 100 },
            plotOptions: {
              series: {
                  color: '#648e59',
                  fillOpacity: 0.8,
                  fillColor: '#648e59',
                  pointInterval: 36e5 * 2 // two hours
                      }
            },
            series: [{
              name: 'Someone1',
              data: [],
            }]
        };
    }
   saveInstance(chartInstance) {
    this.chart = chartInstance;
     console.log(chartInstance);
}

    public ngOnInit () {
    this.dataSubscription = this.userService3.getData().subscribe((data) 
=> {
      this.options.series[0].data = data.data.operating_details;
      console.log(data);
   });
}
    ngOnDestroy() {
      if (this.dataSubscription){
this.dataSubscription.unsubscribe();
}
    }

Here's my html:

   <chart [options]="options" (load)="saveInstance($event.context)"> 
   </chart>

Solution

  • You can simply get the timezone offset from your client:

    const timeZoneOffset = new Date().getTimezoneOffset();
    

    You will get the local difference from UTC in minutes, then use it as you wish. Depending on your type of application, this should be a better approach than hard coding the time zone for most cases when your client are in different time zones.