MySQL日期时间在谷歌图表

MySQL Datetime in Google Chart

本文关键字:谷歌 日期 时间 MySQL      更新时间:2023-09-26

我正在处理MySQL的图表,它作为线形图工作得很好,但当我更改为annotationchart时,它给了我以下错误,因为它需要日期/时间,我将类型更改为datetime(是字符串),仍然有错误。

Type mismatch. Value 2014-07-23 19:03:16 does not match type datetime
原始代码

 <?php
        $con=mysql_connect("ip","user","pass") or die("Failed to connect with database!!!!");
        mysql_select_db("db", $con); 
        $sth = mysql_query("SELECT * FROM db.table");
        $data = array (
      'cols' => array( 
        array('id' => 'date', 'label' => 'date', 'type' => 'datetime'), 
        array('id' => 'Temp', 'label' => 'Temp', 'type' => 'number'), 
        array('id' => 'Humid', 'label' => 'Humid', 'type' => 'number')
    ),
    'rows' => array()
);
while ($res = mysql_fetch_assoc($sth))
    // array nesting is complex owing to to google charts api
    array_push($data['rows'], array('c' => array(
        array('v' => $res['TIME']), 
        array('v' => $res['TEMP']), 
        array('v' => $res['HUMID'])
    )));
?>
<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load('visualization', '1.1', {'packages':['annotationchart']});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
            var bar_chart_data = new google.visualization.DataTable(<?php echo json_encode($data); ?>);
        var options = {
          title: 'Weather Station'
        };
        var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
        chart.draw(bar_chart_data, options);
      }
    </script>
</head>
            <body>
                <div id="chart_div" style="width: 900px; height: 500px;"></div>
            </body>
        </html>

"datetime"数据类型需要非常特定的数据输入语法。当使用JSON时,数据应该以这种格式构建为字符串:'Date(year, month, day, hours, minutes, seconds, milliseconds)',其中month之后的所有选项都是可选的(day默认为1,所有其他选项为0), month是零索引(因此一月是0而不是1)。

你可以这样转换你的日期时间:

while ($res = mysql_fetch_assoc($sth)) {
    // assumes dates are patterned 'yyyy-MM-dd hh:mm:ss'
    preg_match('/('d{4})-('d{2})-('d{2})'s('d{2}):('d{2}):('d{2})/', $res['TIME'], $match);
    $year = (int) $match[1];
    $month = (int) $match[2] - 1; // convert to zero-index to match javascript's dates
    $day = (int) $match[3];
    $hours = (int) $match[4];
    $minutes = (int) $match[5];
    $seconds = (int) $match[6];
    array_push($data['rows'], array('c' => array(
        array('v' => "Date($year, $month, $day, $hours, $minutes, $seconds)"), 
        array('v' => $res['TEMP']), 
        array('v' => $res['HUMID'])
    )));
}

感谢Asgallant和大量的摆弄,下面的代码修复了我所有的问题

    array('v' => 'Date(' . date('Y,n,d,H,i,s', strtotime($res['TIME'])).')'), 
    array('v' => floatval($res['TEMP'])), 
    array('v' => floatval($res['HUMID']))

我找到了一种简化的方法来转换MySQL日期时间到javascript使用PHP日期函数,虽然温度和湿度值存储为MySQL中的小数,javascript不喜欢它,所以我使用floatval使这些工作也。现在我有一个快乐的,工作的注释图!