MySQL的日期时间在谷歌图(MySQL Datetime in Google Chart)

2019-10-20 13:27发布

我的工作从MySQL在图表上,它工作得很好的线型图,但是当我改变annotationchart它给了我下面的错误,由于它需要一个日期/时间,我改变了类型日期时间(为字符串),仍然有错误。

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>

Answer 1:

在“日期时间”数据类型需要数据输入一个非常特殊的语法。 当使用JSON,该数据应被理解为这种格式的字符串: 'Date(year, month, day, hours, minutes, seconds, milliseconds)' ,其中后所有选项month是可选的(默认值是1day0所有其他人)和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'])
    )));
}


Answer 2:

由于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使这些工作也。 现在我有一个幸福,工作注释图!



文章来源: MySQL Datetime in Google Chart