2015-06-22 72 views
2

我有一個帶有日期時間變量的表,它的值類似於其格式爲2015-06-22 22:30:00.030的記錄。更改日期時間以便在codeigniter中進行比較

如何將日期時間轉換爲codeigniter中的日期格式,以便我可以將其與表單中輸入的日期(不包括時間)進行比較?這是我的查詢,這讓我這個錯誤:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'As Date) > '%2015/05/31%' AND merchant_transactions.CAST(datetime As Date) < '%2' at line 7

$search_where = "merchant_transactions.CAST(datetime As Date) > '%".$from."%' AND merchant_transactions.CAST(datetime As Date) < '%".$to."%'"; 

    $this->db->where($search_where); 
    return $this->db->get(); 

回答

4

另一種選擇是使用SQL BETWEEN函數比較日期,但你需要輸入的日期轉換爲日期格式:YYYY-MM-DD

$from = date('Y-m-d', strtotime($from_date)); 
$to = date('Y-m-d', strtotime($to_date)); 
$search_where = 'CAST(merchant_transactions.datetime As Date) BETWEEN "'.$from.'" AND "'.$to.'"'; 
1

您可以使用strtotime解析輸入。我也認爲你的SQL應該改變一點。

$time = '2015/05/31'; 
$from = strtotime($time); 
$m_from = date('m', $from); 
$d_from = date('d', $from); 
$y_from = date('Y', $from); 

$to = strtotime($time); 
$m_to = date('m', $to); 
$d_to = date('d', $to); 
$y_to = date('Y', $to); 

$search_where = "CAST(merchant_transactions.datetime As Date) > '".$y_from."-".$m_from."-".$d_from."' AND CAST(merchant_transactions.datetime As Date) < '".$y_to."-".$m_to."-".$d_to."'";