将日期时间更改为日期以便在 codeigniter 中进行比较

changing datetime to date for comparison in codeigniter

我有一个带有日期时间变量的 table,它的值类似于它有格式为 2015-06-22 22:30:00.030 的记录。

如何在 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();

您可以使用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."'";

另一种选择是使用 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.'"';