以mm / d / y到Y-m-d的格式化日期?

时间:2013-07-12 21:14:21

标签: php mysql date datetime

我正在尝试格式化一个日期字符串,我从网络中删除日期为m / d / y,我需要将其插入MYSQL当前我收到错误PHP致命错误:调用成员函数格式( )在非对象上

代码:

<?php
include 'ganon.php';
$id = array(8573, 53816, 7746, 80748, 7714);

for($l=0; $l<sizeof($id); $l++) {
$html = file_get_dom("http://pregame.com/pregamepros/pro-bettor/picks.aspx?id=" . $id[$l]);

$picks = $html('div[class="div-table-col"]');

$array = array();
$j =0;
for($i=0; $i<sizeof($picks); $i+=8) {
    $array[$j] = array("date" => trim($picks[$i]->getPlainText()), 
            "sport" => trim($picks[$i+1]->getPlainText()),
            "pick" => trim($picks[$i+2]->getPlainText()),
            "score" => trim($picks[$i+3]->getPlainText()),
            "odds" => trim($picks[$i+4]->getPlainText()),
            "size" => preg_replace('/\$/', "", $picks[$i+5]->getPlainText()),
            "winloss" => trim($picks[$i+6]->getPlainText()),
            "money" => (int)preg_replace('/\$/', "", $picks[$i+7]->getPlainText()));
    $j++;
} 

//enter picks into database
//make sure we do not add picks we already have
$mysqli = new mysqli("host", "user", "pass", "db");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    exit();
}
if($id[$l] == 8573) {
//$query = "SELECT `date` FROM `db`.`vegasrunner` where date=" . date('Y-m-d');
for($i=0; $i<sizeof($array); $i++) {
$query = "SELECT `date`,`pick` FROM `db`.`vegasrunner` where date=" . "'" . $array[$i]["date"] . "'" . " AND pick=" . "'" . $array[$i]["pick"] . "'";
$result = $mysqli->query($query);
$row = $result->fetch_row();
if(sizeof($row) < 1) {
    $result->close();
    $date = new DateTime();
    $date = DateTime::createFromFormat('m/d/y', $array[$i]["date"]);
    //$date = $array[$i]["date"];
    $sport = $array[$i]["sport"];
    $pick = $array[$i]["pick"];
    $score = $array[$i]["score"];
    $odds = $array[$i]["odds"];
    $size = $array[$i]["size"];
    $winloss = $array[$i]["winloss"];
    $money = $array[$i]["money"];

    echo $date->format('Y-m-d');

    $query = "INSERT INTO `db`.`vegasrunner` (`date`, `sport`, `pick`, `score`, `odds`, `size`, `winloss`, `money`) VALUES (" . "'" . $date->format('Y-m-d') . "'" . ", '$sport', '$pick', '$score', '$odds', '$size', '$winloss', '$money')";

    $mysqli->query($query);
}
    } }  

2 个答案:

答案 0 :(得分:1)

我能看到的唯一可信的解释是createFromFormat()失败,如果输入日期不符合您期望的格式,则可能会发生这种情况。

检查输入字符串是否符合您的想法,并更改您的代码,以便在createFromFormat()调用时检查失败。

答案 1 :(得分:0)

我最终编写了自己的函数来解析日期。事实证明,这个月之前有一个隐藏的空间。

function formatDate($date) {
    //date = 07/12/13
    $date = explode('/', $date);
    //for some reason in ubuntu month had a space had to get last 2 characters
    $month = substr($date[0], -2);
    $day = trim($date[1]);
    $year = date('y') == $date[2] ? date('Y') : date('Y');

    return $year . "-" . $month . "-" . $day;
}