Home > Articles

  • Print
  • + Share This

Checking the Validity of a Date

Problem

You want to see whether the user has submitted a valid date.

Solution

Use the checkdate() function, which validates a date in the format MM/DD/YYYY:

<?php
list ($month, $day, $year) = explode ('/', $date);

if (checkdate ($month, $day, $year)) {
  print "Valid Date!";
} else {
  print "Not Valid!";
}
?>

Discussion

checkdate() checks the validity of a date according to the following criteria:

  • year is between 0 and 32767, inclusive.

  • month is between 1 and 12, inclusive.

  • day is within the allowed number of days for the given month. Leap years are taken into consideration.

This solution can also be easily implemented in PHP. Here is an example of how it might be done:

<?php

function is_leap_year ($year)
{
  return ((($year%4) == 0 && ($year%100)!=0) || ($year%400)==0);
}

function is_valid_date ($date)
{
  /* Split the date into component parts. */
  list($month, $day, $year) = explode('/', $date);
  $month_days = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

  if ($month < 1 || $month > 12)
    return false;

   /* Year has to consist of 4 digits. */
  if ((strlen($year) != 4) || eregi("[^0-9]", $year))
    return false;

  /* If it's a leap year, February will have 29 days. */
  if (is_leap_year($year))
    $month_days[1] = 29;

  if ($day < 1 || $day > $month_days[$month - 1])
    return false;

  return true;
}
?>

The previous example first splits the date by "/" and assigns the returned array to $month, $day, and $year. Then it simply tests whether each date part is within the specified range. This function also uses a little trick; $day is a string, but when it's compared against numbers, it is automatically converted to a number. So, if $day is not a numerical string, the result of the conversion will be 0, which is outside the specified range.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.