php Datetime Class
Create Immutable version of DateTime from Mutable prior PHP
To create \DateTimeImmutable in PHP 5.6+ use:
\DateTimeImmutable::createFromMutable($concrete);
Prior PHP 5.6 you can use:
\DateTimeImmutable::createFromFormat(\DateTime::ISO8601, $mutable->format(\DateTime::ISO8601),
$mutable->getTimezone());
Add or Subtract Date Intervals
We can use the class DateInterval to add or subtract some interval in a DateTime object.
See the example below, where we are adding an interval of 7 days and printing a message on the screen:
$now = new DateTime();// empty argument returns the current date
$interval = new DateInterval('P7D');//this objet represents a 7 days interval
$lastDay = $now->add($interval); //this will return a DateTime object
$formatedLastDay = $lastDay->format('Y-m-d');
Output
echo "Samara says: Seven Days. You'll be happy on $formatedLastDay.";
Output
getTimestamp
getTimeStemp is a unix representation of a datetime object.
$date = new DateTime();
echo $date->getTimestamp();
Output
setDate
setDate sets the date in a DateTime object.
$date = new DateTime();
$date->setDate(2016, 7, 25);
Create DateTime from custom format
PHP is able to parse a number of date formats. If you want to parse a non-standard format, or if you want your code to explicitly state the format to be used, then you can use the static DateTime::createFromFormat method:
Object oriented style
$format = "Y,m,d";
$time = "2009,2,26";
$date = DateTime::createFromFormat($format, $time);
Procedural style
$format = "Y,m,d";
$time = "2009,2,26";
$date = date_create_from_format($format, $time);