2015-06-22 43 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."'";