所以我有这样的代码:
$date_from = "2017-04-01";
$date_to = "2017-05-01"
$stmt = $this->pdo->prepare("SELECT * FROM records where created_at BETWEEN :start_date AND :end_date");
$stmt->execute([':start_date' => $date_from, ':end_date' => $date_to]);我的created_at是一个timestamp字段。
我这里的问题是,尽管它可以工作,但我只需要在created_at字段中选择月份和年份,因为在我的代码中,日期也包含在选择数据中。例如,我只想要"2017-04" - "2017-5"记录,这样即使像"2017-05-31"这样的记录仍然在"2017-5"下。这里我漏掉了什么?
假设我有一条created_at值为"2017-05-01"的记录。它不会被选中,因为它不在给定的日期之间,这就是为什么我需要修复我的代码,使其只使用月和年,即使给定的日期是日期。
任何帮助都将不胜感激。
发布于 2017-08-15 15:04:42
格式化您的日期时间。
您可以使用字符串比较。
DATE_FORMAT('2017-04-01','%Y%m')返回日期:201704。
因此where子句应该是
"created_at DATE_FORMAT(created_at,'%Y%m') >= DATE_FORMAT($date_from,'%Y%m') and DATE_FORMAT(created_at,'%Y%m') <= DATE_FORMAT($date_to,'%Y%m')“
发布于 2017-08-15 15:00:20
在php甚至mysql中将日期转换为时间戳
PHP:
$date_from_timestamp = strtotime($date_from);
$date_from_timestamp = strtotime($date_to);
MySQL:
UNIX_TIMESTAMP($date_from)
UNIX_TIMESTAMP($date_to)发布于 2017-08-15 14:58:00
$date_from = "2017-04-01";
$date_to = date("Y-m-d",strtotime($date_from." +1 months"));
$stmt = $this->pdo->prepare("SELECT * FROM records where created_at BETWEEN :start_date AND :end_date");
$stmt->execute([':start_date' => strtotime($date_from), ':end_date' => strtotime($date_to]));尝尝这个。如果你的created_at是时间戳。您的搜索条件还需要是时间戳
要在一个月或一年内进行搜索,您可以执行以下操作。
$date_from = "2017-04-01";
$date_to = date("Y-m-d",strtotime($date_from." +1 months")); // to add one month from 2017-05-01https://stackoverflow.com/questions/45687819
复制相似问题