简体   繁体   中英

How do I format the X-Axis dates using UNIX Timestamp with CanvasJS

I am trying to create a candlestick graph with CanvasJs and I am currently having trouble formatting the X Axis correct to show the dates.

I am pulling this data from a database. When I pull the date from the data base I am pulling it as a UNIX Timestamp. I want the X-Axis to show the date for each data point (I want to just do it monthly but I'll worry about that later once I get this). I have tried using "label" and "x" for the date points on the X-Axis.

array_push($dataPoints, array("label"=>$row->day, "y"=> array($row->openPrice, $row->high, $row->low, $row->closePrice)));.

And here is what I have for creating the graph. window.onload = function() {

        var chart = new CanvasJS.Chart("chartContainer", {
            zoomEnabled:true,
            title: {
                text: "Apple Historical Prices"
            },
            axisX: {
                labelFormatter: function (e) {
                    return CanvasJS.formatDate( e.value, "DD MMM");
                },
                valueFormatString: "DD MMM"
            },
            axisY: {
                includeZero: false,
                prefix: "$"
            },
            data: [{
                type: "candlestick",
                xValueType: "dateTime",
                yValueFormatString: "$###.##",
                dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
            }]
        });
        chart.render();

        }

What would I have to change here to correctly format the X-Axis to show the date (convert from UNIX Time Stamp)

Currently it only displays "DEC 31" for each data point.

Zack,

You are passing label and y-value to dataPoints whereas xValueType is applicable for x-values . As you are not passing x-values in dataPoints, library auto-generates it as 1,2,3,4,5... which gives you undesired results in labelFormatter.

You can convert Unix timestamp to JavaScript timestamp by multiplying it by 1000. Then pass that value as 'x' in dataPoints.

array_push($dataPoints, array("x"=>strtotime($row->day)*1000, "y"=> array($row->openPrice, $row->high, $row->low, $row->closePrice)));.

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