In this seventh part of an eight-part article series on handling dates and time with PHP, you'll learn how to use the date function's validators, and how to easily manipulate dates. This article is excerpted from chapter 12 of the book Beginning PHP and PostgreSQL 8: From Novice to Professional, written by W. Jason Gilmore and Robert H. Treat (Apress; ISBN: 1590595475).
Validators
Date offers a method for determining whether the date falls on a leap year and a method for validating the date’s correctness. Both of those methods are introduced in this section.
isLeap()
boolean isLeap()
TheisLeap()method returnsTRUE if the year represented by the date object is a leap year, andFALSEotherwise. The following script usesisLeap()in conjunction with a ternary operator to inform the user whether a given year is a leap year:
$year = 2005; $date = new Date(date("j"),date("n"),$year); echo "$year is ". ($date->isLeap() == 1 ? "" : "not"). " a leap year.";
This produces the following output:
--------------------------------------------2005 is not a leap year. --------------------------------------------
isValid()
boolean isValid()
TheisValid()method returnsTRUEif the date represented by the date object is valid, andFALSEotherwise. Because this method can’t be called statically, and it’s impossible to set an invalid date using the constructor of any of the mutators, it isn’t presently apparent whyisValid()exists.