用户输入的PHP日期转换

时间:2013-12-14 13:23:40

标签: 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" />
<?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);
}

这是输出

日期1 = 2013年12月14日

日期2 = 1970-01-01

日期3 = 2013-12-13

2013年12月13日

我期待第2天是2013-12-13,格式似乎没问题,但价值不是。我玩过许多不同的获取价值的方式,一切都错了! 所以我有两个问题 1.如何在上面的代码中获得正确的值? 2.我想使用此值来搜索MySQL表并返回与其匹配的日期计数。一旦上述工作,这是最好的方式 - 或者有更好的方法吗? 非常感谢

4 个答案:

答案 0 :(得分:0)

来自strtotime手册:

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.

所以:

$newDate = date("Y-m-d", strtotime($_POST['start_date']))

要求第14个月的第12天。

尝试将/替换为

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

答案 1 :(得分:0)

问题是因为遇到/时,strtotime假定时间采用美国格式m/d/Y(而不是d/m/Y)。阅读manual on strtotime(特别是注释)以获取更多信息。

由于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中表示。

答案 2 :(得分:0)

“爆炸”似乎常常在这种情况下使用。

$mydate = $_POST["submit_start"];
list ($y, $m, $d) = explode('/', $mydate);
$mydate = sprintf("%02d-%02d-%04d", $m, $d, $y);

strtotime需要英文日期格式作为输入 - HERE

答案 3 :(得分:0)

strtotime() PHP Manual

看看那里,报告

  

该函数需要一个包含英文日期格式的字符串

这就是为什么你的功能不能按预期工作的原因。事实上,d/m/Y不是美国日期格式。在这里,看一看,我为您提供了一些示例,让您了解如何使其工作:Click here - eval.in

<?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

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

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

进行比较

由于我不知道您的查询,我只会为您提供查询中所需的部分:

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

其中some_datesome_other_date是两种有效的日期格式,如上所述。