2012-12-18 37 views
1

我有一个日期验证器代码段,它应该验证任何未来的日期。为了调试目的,我希望它在Tomorrow过期,或者在大约3个小时内过期。截至撰写这篇明天是12月18日。其10:40 PM GMT-5 Dec 17它将其标记为过去。日期输入3个后期变量:日,月,年和连接,“01:01:59”追加,并作为一个时间戳插入到一个表中,其中预先通过脚本检查,以查看该项目是否已过期。下面的代码不会验证离2天以外的任何日期。我无法弄清楚为什么。PHP:我未来的日期验证器出了什么问题?

代码:

if(check_post('day')&&check_post('month')&&check_post('year')) 
{ 
    //die("day: ".$_POST['day']." month: ".$_POST['month']." year: ".$_POST['year']); 
    if(!check_post('day',"Select Day")&&!check_post('month',"Select Month")&&!check_post('year',"Select Year")) 
    { 
     $days = array("31", "28", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31"); 
     $today = explode("-",date("d-m-Y")); 
     if(checkdate($_POST['month'],$_POST['day'],$_POST['year'])) 
     { 
      $c_y = ($_POST['year']==$today[2]); 
      $c_m = ($_POST['month']==$today[1]); 
      $p_d = ($today[0]>$_POST['day']); 
      $p_m = ($today[1]>$_POST['month']); 
      if(!($c_y&&(($c_m&&$p_d)||$p_m))) 
      { 
       $_POST['date']=strval($_POST['year'])."-".(($_POST['month']>9)?strval($_POST['month']):"0".strval($_POST['month']))."-".(($_POST['day']>9)?strval($_POST['day']):"0".strval($_POST['day'])); 
       $_POST['date'] .= " 01:01:59"; 
       //$_POST['date'] = mktime(0,0,0,$_POST['month'],$_POST['day'],$_POST['year']); 
       //die($_POST['date']); 
      } 
      else 
      { 
       add_error("Date must be current"); 
      } 
     } 
     else 
     { 
      add_error("Invalid expiration date"); 
     } 
    } 
    else 
    { 
     add_error("Pick an expiration date"); 
    } 
} 
else 
{ 
    add_error("Date not set"); 
} 

没有一些功能,这是否对我的权利?

+3

http://php.net/DateTime http://php.net/DateInterval - 就PHP4而言,我投票决定关闭这个问题,因为它太本地化了。 – hakre

+2

即使在PHP4中,['strtotime'](http://php.net/strtotime)也是如此。此外,在PHP4上插入演讲稿*可能过时并且可能不安全,不应该如何使用它,以及任何虚拟主机提供商如何仍然允许它被选择是您不想与之做生意的公司。 – Charles

+0

谢谢查尔斯,我忘记了strtotime。如果您将该帖子作为答案,我可以接受。我似乎错过了很多。 –

回答

2

一个简单的字符串比较会做:

$today = date("Y-m-d"); 
$date = $_POST['year'] . '-' . 
    str_pad($_POST['month'], '0', 2, STR_PAD_LEFT} . '-' . 
    str_pad($_POST['day'], '0', 2, STR_PAD_LEFT); 

if ($date > $today) { 
    // future date 
} else { 
    // something else 
} 

或者:

if (strtotime("{$_POST['year']}-{$_POST['month']}-{$_POST['day']}") > time()) { 
    // future date 
} 

这是不完全一样的,因为time()也有两个日期和时间组成部分,但它应该只是罚款以及。