Date and Time
To Start working with DateTime, convert raw date and time string to an object with createFromFormat() factory method or do new DateTime to get the current date and time. Use format() method to convert Date Time back to a string for output.
<?php $raw = '22. 11. 1968'; $start = DateTime::createFromFormat('d. m. Y', $raw); echo 'Start date: ' . $start->format('Y-m-d') . "\n";
Calculating with DateTime is possible with the DateInterval Class. DateTime has methods like add() and sub(). To calculate date difference use the diff() method.
<?php // create a copy of $start and add one month and 6 days $end = clone $start; $end->add(new DateInterval('P1M6D')); $diff = $end->diff($start); echo 'Difference: ' . $diff->format('%m month, %d days (total: %a days)') . "\n"; // Difference: 1 month, 6 days (total: 37 days)
On DateTime objects, you can use standard comparison:
<?php if ($start < $end) { echo "Start is before the end!\n"; }
DatePeriod Class is used to iterate over recurring events. It can take two DateTime objects, start and end, and the interval for which it will return all events in between.
<?php // output all thursdays between $start and $end $periodInterval = DateInterval::createFromDateString('first thursday'); $periodIterator = new DatePeriod($start, $periodInterval, $end, DatePeriod::EXCLUDE_START_DATE); foreach ($periodIterator as $date) { // output each date in the period echo $date->format('Y-m-d') . ' '; }