Friday, 3 June 2016

Date Validation In PHP

In this post we will see how to validate date in PHP. Date that you want to test may have various Formats Like…

=> YYYY-MM-DD
=> DD/MM/YYYY
=> MM-DD-YYYY
=> DD-MM-YYYY
=> YYYY-MM-DD and so on..

We will see mostly used formats. Date in the other format  can easily be validated by making small changes in the existing code. So, let’s have look at them.

YYYY-MM-DD Format

$date = '2013-05-14';
//Date that needs to be tested goes here

 function isItValidDate($date) {
 if(preg_match("/^(\d{4})-(\d{2})-(\d{2})$/", $date, $matches))  
  {
   if(checkdate($matches[2], $matches[3], $matches[1]))
    { 
     return true;
    }
  }
 } 

if(isItValidDate($date))
 {
   echo 'It’s a valid Date. '; 
 } 
 else
 {
  echo 'Entered Date is invalid..!!'; 
 }

DD/MM/YYYY Format

$date = '14/05/2013'; 
//Date that needs to be tested goes here  

function isItValidDate($date) {
  if(preg_match("/^(\d{2})\/(\d{2})\/(\d{4})$/", $date, $matches))
   {
    if(checkdate($matches[2], $matches[1], $matches[3]))
      {
       return true; 
      }
   }
 }

if(isItValidDate($date))
 {
  echo 'It’s a valid Date';
 }
 else
 {
 echo 'Entered Date is invalid..!!';
 }

MM-DD-YYYY Format

$date = '05-14-2013'; 
//Date that needs to be tested goes here

function isItValidDate($date) {
 if(preg_match("/^(\d{2})-(\d{2})-(\d{4})$/", $date, $matches)) 
  {
  if(checkdate($matches[1], $matches[2], $matches[3]))
   {
    return true;
   }
  }
 }

if(isItValidDate($date)) 
{
 echo 'It’s a valid Date'; 
}
 else
 {
  echo 'Entered Date is invalid..!!';
 }

PHP checkdate function

checkdate

(PHP 4, PHP 5, PHP 7)
checkdate  Validate a Gregorian date

Description 

bool checkdate ( int $month , int $day , int $year )
Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined.

Parameters 

month
The month is between 1 and 12 inclusive.
day
The day is within the allowed number of days for the given month. Leap years are taken into consideration.
year
The year is between 1 and 32767 inclusive.

Return Values 

Returns TRUE if the date given is valid; otherwise returns FALSE.

Examples 

Example #1 checkdate() example
<?php
var_dump
(checkdate(12312000));var_dump(checkdate(2292001));?>
The above example will output:
bool(true)
bool(false)

PHP Date functions

Displaying Present Month

echo date('M');
The output is here.
Jun

Displaying Last Month

echo date('M',strtotime("first day of last month"));
May

Displaying 2nd Last Month

echo date('M',strtotime("last day of -2 month"));
Apr

Present Day of the Week

echo date('l');
The output is here.
Friday

Present Day of the Month

echo date('d');
The output is here.
03

PHP Month year day selection drop down list to generate date format

<?Php
$todo=$_POST['todo'];
if(isset($todo) and $todo=="submit"){
$month=$_POST['month'];
$dt=$_POST['dt'];
$year=$_POST['year'];
$date_value="$month/$dt/$year";
echo "mm/dd/yyyy format :$date_value<br>";
$date_value="$year-$month-$dt";
echo "YYYY-mm-dd format :$date_value<br>";
}

?>
<form method=post name=f1 action=''><input type=hidden name=todo value=submit>
<table border="0" cellspacing="0" >
<tr><td align=left >
<select name=month value=''>Select Month</option> <option value='01'>January</option> <option value='02'>February</option> <option value='03'>March</option> <option value='04'>April</option> <option value='05'>May</option> <option value='06'>June</option> <option value='07'>July</option> <option value='08'>August</option> <option value='09'>September</option> <option value='10'>October</option> <option value='11'>November</option> <option value='12'>December</option> </select>

</td><td align=left >
Date<select name=dt >
<option value='01'>01</option> <option value='02'>02</option> <option value='03'>03</option> <option value='04'>04</option> <option value='05'>05</option> <option value='06'>06</option> <option value='07'>07</option> <option value='08'>08</option> <option value='09'>09</option> <option value='10'>10</option> <option value='11'>11</option> <option value='12'>12</option> <option value='13'>13</option> <option value='14'>14</option> <option value='15'>15</option> <option value='16'>16</option> <option value='17'>17</option> <option value='18'>18</option> <option value='19'>19</option> <option value='20'>20</option> <option value='21'>21</option> <option value='22'>22</option> <option value='23'>23</option> <option value='24'>24</option> <option value='25'>25</option> <option value='26'>26</option> <option value='27'>27</option> <option value='28'>28</option> <option value='29'>29</option> <option value='30'>30</option> <option value='31'>31</option> </select>
</td><td align=left > Year(yyyy)<input type=text name=year size=4 value=2005> <input type=submit value=Submit> </table> </form>

Tested in June month
for($i=0;$i<=11;$i++){
$month=date('M',strtotime("first day of -$i month")); // Month name with 3 letters
echo $month ."<br>";
}
?>
Output is here
Jun
May
Apr
Mar
Feb
Jan
Dec
Nov
Oct
Sep
Aug
Jul
<?php
echo "<select name=month>";
for($i=0;$i<=11;$i++){
$month=date('F',strtotime("first day of -$i month")); // Month full name
echo "<option value=$month>$month</option> ";
}
echo "</select>";
?>

June
May
April
March
February
January
December
November
October
September
August
July

<?php
//Listing next 5 years starting from present year
echo "<select name=year>";
for($i=0;$i<=5;$i++){
$year=date('Y',strtotime("last day of +$i year"));
echo "<option name='$year'>$year</option>";
}
echo "</select>";
?>

PHP Display next 10 months and past 10 months including this month with year

<?php
for ($i=0; $i<10; $i++)
{
    $timestamp = mktime(0,0,1,date("m")+$i,date("d"),date("Y"));
    $month = date("F Y", $timestamp);
    echo "{$month}<br />\n";

?>

For Past 10 months including this month
Filter by month:<select name="month">
<option value="?month=">All months</option>
<?php
$beginning_month = 10;
for($x=0;$x<$beginning_month;$x++){

    $time = strtotime("$x months ago");
    $month = date("F Y",$time);
    $link = strtolower(date("MY",$time));
   
    if(isset($_GET['month']) && $link == $_GET['month']) {
        
        echo '<option value="'.$link.'" selected="selected">'.$month.'</month>';
   
    } else {
    echo '<option value="'.$link.'">'.$month.'</month>';
    }
}

echo '</select>';
echo '<input type="submit" value="Filter" />'; 
?>


PHP Month full names dropdown

<?php
$monthArray = range(1, 12);
?>
<select name="month">
    <option value="">Select Month</option>
 <?php  
    foreach ($monthArray as $month) {
        // padding the month with extra zero
        $monthPadding = str_pad($month, 2, "0", STR_PAD_LEFT);
        // you can use whatever year you want
        // you can use 'M' or 'F' as per your month formatting preference
        $fdate = date("F", strtotime("2015-$monthPadding-01"));
        echo '<option value="'.$monthPadding.'">'.$fdate.'</option>';
    }
?>  
</select>

Year dropdown from current year to 2013 and Month dropdown with leading zero

Year Dropdown from current year to 2013
<?php
$earliest_year = 2013;
$latest_year = date('Y');
?>
<select name="filterYear" id="filterYear"  style="width:130px">            
         <?php
             foreach ( range( $latest_year, $earliest_year ) as $i ) {
         ?>
         <option value="<?php echo $i; ?>" <?php echo ((int)$i === (int)$filterYear ? ' selected="selected"' : ''); ?>><?php echo $i; ?></option>
         <?php
         }
         ?>
         </select>
Month Dropdown with leading zero upto 10th month
<?php
$numZeroesToAppend =2;
?>
<select name="filterMonth" id="filterMonth"  style="width:130px">
               <?php
                   for($m=1;$m<=12;$m++){       

                    $mUpdated = str_pad($m, $numZeroesToAppend, '0', STR_PAD_LEFT);
              ?>
                <option <?php echo ((int)$filterMonth == (int)$mUpdated)?"selected":""; ?> value="<?php echo $mUpdated; ?>"><?php echo $mUpdated; ?></option>
              <?php
                }
                ?>
               </select>