日期未正确格式化为字符串

时间:2017-06-02 06:17:19

标签: php jquery

在此代码中,我将日期格式dd-mm-yy转换为yy-mm-dd。当我回显$from日期时,它会给出正确的日期(2017-6-1)。与echo $to类似。  但是,当我回显查询时,它无法获得$from的值,但是$to它会正确获取日期。 $from有什么问题?

这是我的代码......

<script language='javascript'>
    jQuery(function($)
           { 
               $("#from").datepicker({ dateFormat: 'dd-mm-yy' });
               $("#to").datepicker({ dateFormat: 'dd-mm-yy' });
           });
</script>

<input name="from" id="from" type="text" />
<input name="to" id="to" type="text" />

<?php
    $froms = $_POST['from'];
    list($day, $month, $year) = explode("-", $froms);
    $from = "$year-$month-$day";

    $too = $_POST['to'];
    list($day, $month, $year) = explode("-", $too);
    $to = "$year-$month-$day";

    if($from = "$year-$month-$day" && $to = "$year-$month-$day")
    {
        echo "select * from students where (enquiry_date between '$from' and '$to')";
    }
?>

结果:

select * from students where (enquiry_date between '1' and '2017-06-09') order by student_id

2 个答案:

答案 0 :(得分:4)

首先,您需要使用&#39; ==&#39;而不是&#39; =&#39;当你比较时。

否则,我认为您正在尝试检查日期格式是否输入正确。

如果是,请替换line:

if($from = "$year-$month-$day" && $to = "$year-$month-$day")

这一行:

if(validateDate($from) && validateDate($to))

并确保定义函数validateDate:

function validateDate($date)
{
    $d = DateTime::createFromFormat('Y-m-d', $date);
    return $d && $d->format('Y-m-d') == $date;
}

函数已从此answerphp.net

复制

答案 1 :(得分:0)

日期格式化的用户PHP日期功能:

<?php
    $froms = $_POST['from'];
    $from = date('Y-m-d', strtotime($froms));

    $too = $_POST['to'];
    $to  = date('Y-m-d', strtotime($too ));

    echo "select * from students where (enquiry_date between '".$from."' and '".$to."')";
?>