用户输入的PHP日期转换

用户输入的PHP日期转换,php,Php,我试图转换一个用户输入的日期,以便我可以使用它在MySQL中搜索。这是我的密码- <form name="date_form" action="" method="POST""> <input type="text" name="start_date" value="<?php echo date('d/m/Y');?>"/> <input type="submit" name="submit_start" value="Submit" /> &l

我试图转换一个用户输入的日期,以便我可以使用它在MySQL中搜索。这是我的密码-

<form name="date_form" action="" method="POST"">
<input type="text" name="start_date" value="<?php echo date('d/m/Y');?>"/>
<input type="submit" name="submit_start" value="Submit" />
<?php 
if(isset($_POST["submit_start"]))
{
$date_1 = mysqli_real_escape_string($dbc, trim($_POST['start_date']));//checking that I am getting something from the input
$newDate = date("Y-m-d", strtotime($_POST['start_date']));//converting date from the input to SQL format
echo '<br>date 1 = '.$date_1.'<br>';
echo 'date 2 = '.$newDate.'<br>';
$start_date = '2013-12-13';
echo 'date 3 = '.$start_date.'<br>';//Just to compare formats

$report = create_user_report($dbc, $start_date);
}

STROTIME手册中的

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between
the various components: if the separator is a slash (/), then the American m/d/y is 
assumed;     whereas if the separator is a dash (-) or a dot (.), then the European d-m-y
format is assumed.
因此:

要求14个月的第12天

尝试将/替换为-

$date = str_replace ( '/' , '-' , $_POST['start_date'])

造成此问题的原因是,当遇到
/
时,
strotime
假定时间为美国格式的
m/d/Y
(而不是
d/m/Y
)。有关更多信息,请阅读(特别是注释)

由于
14/12/2013
在美国格式中无效,您将获得默认时间(又称UNIX时间戳
0

由于这是用户输入,您无法确定他是否真的打算使用美国格式或误用美国格式,因此您可以在转换之前进行如下检查

//check if input is a date in the American format
if (preg_match("#^(\d+)/(\d+)/(\d+)$#", $_POST['start_date'], $matches)) {
    if ($matches[1] > $matches[2]) {
        $day = $matches[1];
        $month = $matches[2];
    } else {
        $day = $matches[2];
        $month = $matches[1];
    }
    $start_date = $month.'/'.$day.'/'.$matches[3];
}
然而,如果用户输入,例如
04/05/2013
,这将被解释为美国格式,尽管用户可能在
d/m/Y

中表示“爆炸”似乎在类似情况下常用

$mydate = $_POST["submit_start"];
list ($y, $m, $d) = explode('/', $mydate);
$mydate = sprintf("%02d-%02d-%04d", $m, $d, $y);
STROTIME需要英文日期格式作为输入-。

看看那边,它报道

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

这就是为什么你的函数不能像你期望的那样工作。事实上,
d/m/Y
不是美国的日期格式。在这里,看一看,我为您提供了一些示例,让您了解如何使其工作:

因为你永远不知道用户可能输入什么样的日期格式(或者如果它实际上是一个日期),我建议你在输入中使用一个日期选择器插件,这将非常有用,或者你可能想使用其他用户建议的正则表达式

对于mysql部分,您可以轻松地将两个日期与

因为我不知道您的查询,所以我只提供您在查询中进行比较所需的部分:

... WHERE DATE(some_date) = DATE(some_other_date) ...

其中
some_date
some_other_date
是上述两种有效的日期格式。

对于第二个问题,请提供更多信息(通过编辑问题)。您的db模式是什么样子的?单元格的日期类型是否正确?这可能对你有帮助。谢谢大家的帮助。我没有意识到这个/或-会带来不同。我将添加一个javascript日历,以防止用户输入的格式不同。帮了大忙。
<?php 
  echo strtotime(date('m/d/Y'));
  echo strtotime(date('d/m/Y'));
  echo strtotime(date('d-m-Y'));
  echo strtotime(date('d/m/Y'));
  echo strtotime(date('Y-m-d'));
  echo strtotime(date('Y/m/d'));
?>
1386979200

FALSE

1386979200

FALSE

1386979200

1386979200
... WHERE DATE(some_date) = DATE(some_other_date) ...