dongyuan3094
2017-06-02 06:17
浏览 23
已采纳

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

In this code I am converting date format dd-mm-yy to yy-mm-dd. When I echo $from date it gives the correct date (2017-6-1). Similarly with echo $to. But when I echo the query it can't get value of $from, but $to it gets the date correctly. What is the problem with $from?

Here is my code...

<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')";
    }
?>

Result:

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

图片转代码服务由CSDN问答提供 功能建议

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

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

 &lt; script  language ='javascript'&gt; 
 jQuery(function($)
 {
 $(“#from”)。datepicker({dateFormat:'dd-mm-yy'}); 
 $(“#to  “).datepicker({dateFormat:'dd-mm-yy'}); 
}); 
&lt; / script&gt; 
 
&lt; input name =”from“id =”from“type =”text“  /&gt; 
&lt; input name =“to”id =“to”type =“text”/&gt; 
 
&lt;?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“&amp;&amp; $ to =”$ year- $ month- $ day“)
 {
 echo”select * from students where(enquiry_date in'$ from'和'$ to  ')“; 
} 
?&gt; 
   
 
 

结果:

  select * from students where  (在'1'和'2017-06-09'之间的enquiry_date)由student_id订购 
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dourao1877 2017-06-02 06:22
    最佳回答

    First of all, you need to use '==' instead of '=' when you are comparing.

    Otherwise, I think you are trying to check if the date format is entered correctly.

    If so, replace line:

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

    with this line:

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

    and make sure you define the function validateDate:

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

    function was copied from this answer or php.net

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题