How to check if a date is expired (PHP)

13,654

Solution 1

You can use mktime() or strtotime()

$input_time = mktime(0,0,0,$_POST['m']+1,0,$_POST['y']); 

if ($input_time < time()){
   print '<p class = "error">Date has elapsed</p>';

}

Solution 2

You could probably use the strtotime function like this:

$input_date = "$_POST['m']/$_POST['y']"; 
$todays_date = date("m/Y");

if (strtotime($input_date) < strtotime($todays_date)){
print '<p class = "error">Date has elapsed</p>';

}

You can read here what kind of formats strtotime can handle: http://php.net/manual/en/function.strtotime.php

Solution 3

I don't believe that you can put those $_POST variables in quotes. For instance, the following code will crash:

<?php
$foo = array("foo" => "bar");
$input = "$foo['foo']";
print $input;
?>

Instead, try

$input_date = $_POST['m'] . "/" . $_POST['y'];

Also, you may want to consider reversing month and year. In the current scheme 01/13 comes before 12/12.

Share:
13,654
M9A
Author by

M9A

Updated on June 14, 2022

Comments

  • M9A
    M9A almost 2 years

    Hi my php script has two textboxes (one for month and one for year). When the user presses the submit button, it should verify the inputs to see if the dates are expired. Here is the code I made, but it doesnt seem to do anything.

    $input_date = "$_POST['m']/$_POST['y']"; 
    
    $todays_date = date("MM/YY");
    
    if ($input_date < $todays_date)
    {
       print '<p class = "error">Date has elapsed</p>';
    }
    

    Note: the date format is MM/YYYY (textbox 'm' contains MM and tetxbox 'y' contains YYYY)

  • Bojangles
    Bojangles about 12 years
    Do note that MM/YY will give something like AprApr/20122012 - it should just be M/Y.
  • jeroen
    jeroen about 12 years
    According to the manual Values greater than 12 reference the appropriate month in the following year(s).. So if you use $_POST['m'] + 1 you are generating a timestamp the first second of the next month and that is exactly what you want.
  • M9A
    M9A about 12 years
    this works but is it possible to have another variable that converts it back to the "mm/yyyy" format?