2017-09-15 222 views
1

我得到准确的结果,如果我设定开始日期和结束日期时,年份是2017年。但是,当开始日期15月-201615日至2017年它不工作,并显示错误MESSAGE-笨开始和结束日期验证

$error = "End date can't be older than begin date "; 

这里是我的代码

 $data['beginDate'] = $this->input->post('beginDate'); 
     $data['endDate'] = $this->input->post('endDate'); 

     if($data['endDate'] < $data['beginDate']){ 
      $error = "End date can't be older than begin date "; 
      $this->session->set_flashdata('error', $error); 
      redirect('/search'); 
     } 
     else{ 
      $this->load->model('personhistory'); 
      $data['rets'] = $this->personhistory->searchDetails(); 
      $data['sum'] = $this->personhistory->searchDetailsSum(); 
      $data['title'] = "Search Details"; 
      $this->load->view('search_results', $data); 
     } 

有什么解决方案来摆脱这个问题的?请帮助...

+0

请清楚地了解你的测试/例子输入是什么。导致错误的'$ data ['beginDate']'和'$ data ['endDate']'的确切值是什么? –

+0

这些值是使用JQuery日历选择的日期 – user3311692

+0

您有时间机器吗?我不这么认为。十月总是在我的日历上九月之后。 –

回答

0

PHP不知道你的字符串是什么,如果值从发布的数据到来,那么他们都是字符串:

// These are strings 
$s1 = '15-October-2016'; 
$s2 = '15-September-2016'; 

相反,你需要为创建datetime对象的比较

$d1 = new DateTime('15-October-2016'); 
$d2 = new DateTime('15-September-2016'); 

if($d1 < $d2) 
    echo 'First date comes before the second date'; 

if($d1 > $d2) 
    echo 'First date comes after the second date'; 

if($d1 == $d2) 
    echo 'First date and second date are the same'; 

试试这段代码并改变日期,你会看到我是对的。

UPDATE:

从技术上讲,你也可以使用的strtotime

<?php 

$s1 = strtotime('15-October-2016'); 
$s2 = strtotime('15-September-2016'); 

if($s1 < $s2) 
    echo 'First date comes before the second date'; 

if($s1 > $s2) 
    echo 'First date comes after the second date'; 

if($s1 == $s2) 
    echo 'First date and second date are the same'; 
+0

对不起,我的错误... 第二次约会不会** ** 2016年9月15日**,它将** ** 2017年9月15日** 我不'如果日期是** 2016年10月14日**而不是** ** 2016年10月15日**我的代码工作正常,那么请告诉我们是什么样的问题。 @BrianGottier – user3311692

+0

我不知道你是否阅读我的任何评论,甚至试过我的代码,但我向你解释了为什么你的代码无法正常工作。这是因为你试图将日期作为字符串进行比较。我为您提供了两种选择,而且两种都适合您。第一种选择是使用PHP的DateTime类,另一种选择是使用PHP的strtotime函数。你有没有尝试过这些?如果你不能认识到我的答案是好的,我没有任何理由继续帮助你。试试这些代码,并根据需要进行修改。你会看到它适合你。 –

相关问题