Since version 5.2, PHP has provided a DateTime class that can handle much more date and time information at the same time, rather than working with separate date and time functions. Also, it works hand-in-hand with the new DateTimeZone class.
$now = new DateTime("time", obj_timezone);This creates an instance of the DateTime class and stores it in a DateTime object called $now. The DateTime object is aware not only of the date and time it was created but also of the time zone used by the web server.
$object->property or $object->method()
The DateTime object uses only methods, here is some examples:
<?php // get and output the current date/time $date = new DateTime(); echo $date->format('Y-m-d H:i:s'); // 2011-03-21 14:08:00 // output the day of the week of a specified date $date = new DateTime('15-10-2012'); // can also be used: "15-October-2012", "2012-Oct-15" echo '<br /> 15-10-2012 ia a '. $date->format('l'); // 15-10-2012 ia a Monday ?>Output:
<?php // set a new date and time and display it $date = new DateTime(); // set a new date $date->setDate(2012, 10, 15); // set a new time $date->setTime(12, 32); echo $date->format('Y-m-d H:i:s'); ?>Output:
<?php $date = new DateTime(); echo 'Current Timestamp: '. $date->getTimestamp(); ?>Outputs something like:
<?php $date = new DateTime(); echo 'Current date/time: '. $date->format('Y-m-d H:i:s'); $date->setTimestamp(1178902725); echo '<br /> Date time of the 1178902725 timestamp: '. $date->format('Y-m-d H:i:s'); ?>Outputs something like:
<?php // get and display the current time in Pacific/Auckland $dtz = new DateTimeZone('Pacific/Auckland') ; $date = new DateTime(NULL, $dtz); echo $date->format('H:i:s'); // 01:58:02 ?>Outputs something like:
<?php // set an object with the current date $dateNow = new DateTime(); $now = $dateNow->format("Y-m-d H:i"); // store the currend date // the second date $date2 = new DateTime('1996-07-07 14:45:00'); // apply the diff() method, getting a DateInterval object ($diDiff) $diDiff = $dateNow->diff($date2) ; echo 'The difference between: '. $now. ' and "1996-07-07 14:45" is: '. $diDiff->format('%y year, %m months, %d days, %h hours, and %i minutes.'); ?>This code will output something like:
<ul> <li>http://coursesweb.net/html/</li> <li>http://coursesweb.net/css/</li> </ul>
.some_class { display: list-item; }
var obj = { "courses": ["php", "javascript", "ajax"] }; var jsonstr = JSON.stringify(obj); alert(jsonstr); // {"courses":["php","javascript","ajax"]}
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>'; $dochtml = new DOMDocument(); $dochtml->loadHTML($strhtml); $elm = $dochtml->getElementById("dv1"); echo $elm->nodeValue; // CoursesWeb.net