PHP日期转换函数的月和日值问题


php date convert functions problems with month and day value

我从web表单中接收日期值,格式为dd/mm/YY (jquery datepicker)示例:13/07/2014

$date_from = $_POST['date_from'];
$date_to = $_POST['date_to'];
$newdate1 = date("Y-m-d 00:00:00", strtotime($date_from));
$newdate2 = date("Y-m-d 23:59:59", strtotime($date_to));

我需要从数据库中打印所有记录,其中日期在这两个日期之间:

SELECT * FROM db WHERE date BETWEEN '$newdate1' AND '$newdate2'"

它工作得很好,直到今天,因为当我尝试选择今天的日期13/04/1014(在jquery中)并转换为格式Y-m-d 00:00:00脚本认为13是月和返回日期1970-01-01

函数strtotime期望得到一个包含英文日期格式的字符串。

一个基本的解决方案是将你的格式转换成英文格式

echo date('d-m-Y', strtotime(str_replace('/', '-', '13/07/2014');

输出
13-07-2014

在你的代码

$date_from = $_POST['date_from'];
$date_to = $_POST['date_to'];
$newdate1 = date("Y-m-d 00:00:00",strtotime(date('d-m-Y', strtotime(str_replace('/', '-', $date_from)))));
$newdate2 = date("Y-m-d 00:00:00",strtotime(date('d-m-Y', strtotime(str_replace('/', '-', $date_to)))));

由于SQL查询所需的格式与输入格式不同,因此它将在多个日期产生问题。最好先将日期转换为合适的格式,然后再运行查询。

<?php
//Creating a function to convert date to required format
function formattedDate($dateStr, $inputFormat, $outputFormat) {
    $date = DateTime::createFromFormat($inputFormat, $dateStr);
    echo $date->format($outputFormat);
}
//Get input
$date_from = $_POST['date_from'];
$date_to = $_POST['date_to'];
//Get formatted date values
$newdate1 = formattedDate($date_from, "d/m/Y", "Y-m-d H:i:s");
$newdate2 = formattedDate($date_to, "d/m/Y", "Y-m-d H:i:s");
?>