11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 12 • DATE AND TIMEwww.it-ebooks.infoIntroducing the DateTime ConstructorBefore you can use the DateTime class' features, you need to instantiate a date object via its classconstructor. This constructor’s prototype follows:object DateTime([string time [, DateTimeZone timezone]])The DateTime() method is the class constructor. You can set the date either at the time ofinstantiation or later by using a variety of mutators (setters). To create an empty date object (which willset the object to the current date), just call DateTime() like so:$date = new DateTime();To create an object and set the date to May 25, 2010, execute the following:$date = new DateTime("25 May 2010");You can set the time as well, for instance to 9:55 p.m., like so:$date = new DateTime("25 May 2010 21:55");Or you can just set the time like so:$date = new DateTime("21:55");In fact, you can use any of the formats supported by <strong>PHP</strong>’s strtotime() function, introduced earlierin this chapter. Refer to the <strong>PHP</strong> manual for additional examples of supported formats.The optional timezone parameter refers to the time zone as defined by a DateTimeZone class (alsopart of <strong>PHP</strong> as of the 5.1 release). As of 5.1.0, an error of level E_NOTICE will be generated if thisparameter is set to an invalid value, or is NULL, potentially in addition to an error of level E_WARNING if<strong>PHP</strong> is forced to refer to the system's time zone settings.Formatting DatesTo format the date and time for output, or easily retrieve a single component, you can use the format()method. This method accepts the same parameters as the date() function. For example, to output thedate and time using the format 2010-05-25 09:55:00pm you would call format() like so:echo $date->format("Y-m-d h:i:sa");Setting the Date After InstantiationOnce the DateTime object is instantiated, you can set its date with the setDate() method. The setDate()method sets the date object’s day, month, and year, returning TRUE on success and FALSE otherwise. Itsprototype follows:Boolean setDate(integer year, integer month, integer day)Let’s set the date to May 25, 2010:284

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!