note 95830 added to class.datetime

From: Date: Sun, 24 Jan 2010 16:53:46 +0000
Subject: note 95830 added to class.datetime
Groups: php.notes 
Request: Send a blank email to php-notes+get-165253@lists.php.net to get a copy of this message
Small but powerful extension to DateTime <?php class Blar_DateTime extends DateTime { /** * Return Date in ISO8601 format * * @return String */ public function __toString() { return $this->format('Y-m-d H:i'); } /** * Return difference between $this and $now * * @param Datetime|String $now * @return DateInterval */ public function diff($now = 'NOW') { if(!($now instanceOf DateTime)) { $now = new DateTime($now); } return parent::diff($now); } /** * Return Age in Years * * @param Datetime|String $now * @return Integer */ public function getAge($now = 'NOW') { return $this->diff($now)->format('%y'); } } ?> Usage: <?php $birthday = new Blar_DateTime('1879-03-14'); // Example 1 echo $birthday; // Result: 1879-03-14 00:00 // Example 2 echo '<p>Albert Einstein would now be ', $birthday->getAge(), ' years old.</p>'; // Result: <p>Albert Einstein would now be 130 years old.</p> // Example 3 echo '<p>Albert Einstein would now be ', $birthday->diff()->format('%y Years, %m Months, %d Days'), ' old.</p>'; // Result: <p>Albert Einstein would now be 130 Years, 10 Months, 10 Days old.</p> // Example 4 echo '<p>Albert Einstein was on 2010-10-10 ', $birthday->getAge('2010-10-10'), ' years old.</p>'; // Result: <p>Albert Einstein was on 2010-10-10 131 years old.</p> ?> ---- Server IP: 217.160.72.57 Probable Submitter: 85.179.179.215 ---- Manual Page -- http://www.php.net/manual/en/class.datetime.php Edit -- https://master.php.net/note/edit/95830 Del: integrated -- https://master.php.net/note/delete/95830/integrated Del: useless -- https://master.php.net/note/delete/95830/useless Del: bad code -- https://master.php.net/note/delete/95830/bad+code Del: spam -- https://master.php.net/note/delete/95830/spam Del: non-english -- https://master.php.net/note/delete/95830/non-english Del: in docs -- https://master.php.net/note/delete/95830/in+docs Del: other reasons-- https://master.php.net/note/delete/95830 Reject -- https://master.php.net/note/reject/95830 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#165253) next »