所以我有这段代码:
$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"
的记录。它不会被选中,因为它不在给定的日期之间,这就是为什么我需要修改我的代码只使用数月和数年,即使给定的日期是日期。
非常感谢任何帮助。
答案 0 :(得分:2)
格式化您的日期时间。
您可以使用字符串比较。
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')
“
答案 1 :(得分:1)
将您的日期转换为php或甚至mysql中的时间戳
PHP:
$date_from_timestamp = strtotime($date_from);
$date_from_timestamp = strtotime($date_to);
MySQL:
UNIX_TIMESTAMP($date_from)
UNIX_TIMESTAMP($date_to)
答案 2 :(得分:0)
$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-01
答案 3 :(得分:0)
我假设你忽略了输入日,并要求获得4月和5月的记录
$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("Y-m-01 00:00:00",strtotime($date_from)),
':end_date' => date("Y-m-31 23:59:59",strtotime($date_to))
]);