Search code examples
javascriptarraysamchartsamcharts4

How can I convert timestamps toUTCString and prevent browser changing the date to local timezone?


I'm having an array full of timestamps like:

let tAxe = [1548546272000, 1548546287000, 1548546303000, 1548546318000, 1548546333000];

I'm trying to convert each timestamp to a human readable date. Can I prevent this date to be converted by the browser to current timezone? This tAxe variable is used in an amChart4 library to generate the graph.

I'm thinking of a loop but I'm not sure how to write exactly the code

for (i = 0; i < tAxe.length; i++) { 
  // I don't know how to write exactly the conversion

}

Solution

  • You can just set dateFormatter.utc to true and amCharts will do the rest for you:

    chart.dateFormatter.utc = true;
    

    Here is an example using the timestamps you shared:

    am4core.useTheme(am4themes_animated);
    
    var chart = am4core.create("chartdiv", am4charts.XYChart);
    
    chart.dateFormatter.utc = true;
    
    chart.data = [
      {date:1548546272000, value: 12},
      {date:1548546287000, value: 15},
      {date:1548546303000, value: 13},
      {date:1548546318000, value: 17},
      {date:1548546333000, value: 14},
    ];
    
    var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
    
    var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
    
    var series = chart.series.push(new am4charts.LineSeries());
    series.dataFields.valueY = "value";
    series.dataFields.dateX = "date";
    #chartdiv {
      width: 100%;
      height: 500px;
    }
    <script src="https://www.amcharts.com/lib/4/core.js"></script>
    <script src="https://www.amcharts.com/lib/4/charts.js"></script>
    <script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>
    <div id="chartdiv"></div>

    Here is a code pen which also shows the example.