In this sixth part of an eight-part article series on working with time and dates in PHP, you'll study the date constructor in depth, and learn about accessors and mutators. 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).
The Date Constructor
Before you can use the Datefeatures, you need to instantiate a date object via its class constructor. This constructor is introduced in this section.
object date ([integer day [, integer month [, integer year [, integer weekstart]]]])
Thedate()method is the class constructor. You can set the date either at the time of instantiation by using theday,month, andyearparameters, or later by using a variety of mutators (setters), which are introduced next. To create an empty date object, just calldate()like so:
$date = new Date();
To create an object and set the date to April 29, 2005, execute:
$date = new Date(29,4,2005);
You can use the optionalweekstart parameter to tell the object which day of the week should be considered the first. By default, date objects assume the week begins with Monday, meaning Monday has the offset 1.
Curiously, there is no convenient means for setting the date object to the current date. To do so, you need to use thedate()function: