[英]How to select records between two dates using only month and year in PHP and MySQL?
所以我有這個代碼:
$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"
。 它不會被選中,因為它不在給定的日期之間,這就是為什么我需要修改我的代碼只使用幾個月和幾年,即使給定的日期是日期。
任何幫助將非常感激。
格式化您的日期時間。
您可以使用字符串比較。
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')
“
將您的日期轉換為php或甚至mysql中的時間戳
PHP:
$date_from_timestamp = strtotime($date_from);
$date_from_timestamp = strtotime($date_to);
MySQL:
UNIX_TIMESTAMP($date_from)
UNIX_TIMESTAMP($date_to)
$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
我假設你忽略了輸入日,並要求獲得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))
]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.