new Date()不适用于canvasjs& rangeBar

时间:2017-06-06 16:26:18

标签: php json canvas canvasjs

我尝试用PHP代码从AJAX json格式读取一些数据。

.../...
    $data[]     = array("label" => $my_label, "y" => array("new Date($yci,$mci,$dci,$hci,$ici)","new Date($yco,$mco,$dco,$hco,$ico)"));
}

return json_encode($data, JSON_NUMERIC_CHECK);

Side JS

var chart = new CanvasJS.Chart("timeline", {
    title: {
        text: "How long an event occurred for on a given day"
    },
    axisY: {
        minimum: (new Date(2017, 5, 1, 00, 01)).getTime(),            
        interval: (24 * 60 * 60 * 1000 * 7 ),
        labelFormatter: function(e){
        return CanvasJS.formatDate(e.value, "MM/DD");
        },
        gridThickness: 1
    },

    toolTip:{
        contentFormatter: function ( e ) {
        return "<strong>" + e.entries[0].dataPoint.label + "</strong></br> Start: " +  CanvasJS.formatDate(e.entries[0].dataPoint.y[0], "DD - h:mm TT") + "</br>End : " + CanvasJS.formatDate(e.entries[0].dataPoint.y[1], "DD - h:mm TT");  
    }},

    data: [
    {
      type: "rangeBar",
    dataPoints: JSON.parse(json.message),
    }
    ]                      
});
chart.render();

}

问题是,无法显示数据。 我认为新约会没有严格形成。

[
{
    "label":"Room 200",
    "y":
         [
            "new Date(2017,5,06,14,20)",
            "new Date(2017,5,08,14,20)"
         ]
 },
 {
    "label":"Room 200",
    "y":
        [
            "new Date(2017,5,08,14,21)",
            "new Date(2017,5,10,14,21)"
        ]
},
{
    "label":"Room 201",
    "y":
        [
            "new Date(2017,5,11,15,59)",
            "new Date(2017,5,13,15,59)"
        ]
}
]

另外,来自canvasjs示例的新date()有些奇怪,在每个代码的末尾, .getTime()就像这样: new date()。getTime()

http://jsfiddle.net/canvasjs/xqgja576/

你能帮我吗?

2 个答案:

答案 0 :(得分:1)

您在数组中提供的y值是字符串(&#34; new Date(2017,5,06,14,20)&#34;)。要将此y值评估为日期,您可以使用eval函数。此外,CanvasJS不支持dateTime而非yAxis。作为一种变通方法,您可以调用getTime()来获取它的时间戳并将其设置为y值。

for (var i = 0; i < dataPoints.length; i++) {
  for (var j = 0; j < dataPoints[i].y.length; j++) {
    y = eval(dataPoints[i].y[j]);
    //if(y.getTime)
    dataPoints[i].y[j] = y.getTime();
  }
}

以下是包含您的代码和更改的jsfiddle

答案 1 :(得分:1)

您应该只将日期从后端传递为UTC时间戳,因此,您不需要任何客户端转换:

$start = new \DateTime("$yci/$mci/$dci $hci:$ici", new \DateTimeZone("UTC"));
$end = new \DateTime("$yco/$mco/$dco $hco:$ico", new \DateTimeZone("UTC"));
$data[] = array(
    "label" => $my_label, 
    "y" => array(
        // don't forget for '*1000 part' to convert
        // from unix timestamp (seconds) to UTC timestamp (milliseconds)
        $start->getTimestamp() * 1000,
        $end->getTimestamp() * 1000,
     ),
);

此外,您需要根据您的代码考虑正确的DateTime对象初始化(可能,您已经在代码中的某个位置使用了日期时间对象,并为了方便起见将它们解构为$yci, $mci, $dci, $hci, $ici个变量)。您可以使用this手册页作为参考。