Question

I have a date validator code segment, its supposed to validate any future date. For debugging purposes I want it to expire by Tomorrow, or in about 3 hours. As of writing this Tomorrow is Dec 18. Its 10:40PM GMT-5 Dec 17 It flags it as the past. dates get entered with 3 post variables: day, month, year and are concatenated, "01:01:59" appended, and inserted as a timestamp into a table, where its preiodically checked by a script to see if the item has expired. The code below will not validate any date closer than 2 days away. I can't figure out why.

code:

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

There isn't some function that does this for me right?

Was it helpful?

Solution

A simple string comparison will do:

$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
}

Or:

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

This is not entirely the same because time() also has both a date AND time component, but it should work just fine as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top