Once you’ve got a DateTime object that represents a particular point in time, it’s straightforward to do date or time calculations. You might want to give a user a set of dates or times to choose from in a menu. Example 15-6 displays an HTML <select> menu where each choice is a day. The first choice is the date corresponding to the first Tuesday after the program is run. The subsequent choices are every other day after that.
Example 15-6. Displaying a range of days
$daysToPrint = 4;
$d = new DateTime(‘next Tuesday’);
print “<select name=’day’>\n”;
for ($i = 0; $i < $daysToPrint; $i++) {
print ” <option>” . $d->format(‘l F jS’) . “</option>\n”;
// Add 2 days to the date
$d->modify(“+2 day”);
}
print “</select>”;
In Example 15-6, the modify() method changes the date inside the DateTime object at each pass through the loop. The modify() method accepts a string holding one of the relative date/time formats described at http://www.php.net/ datetime.formats.relative and adjusts the object accordingly. In this case, +2 day bumps it forward two days each time.
On October 20, 2016, Example 15-6 would print:
<select name=’day’>
<option>Tuesday October 25th</option>
<option>Thursday October 27th</option>
<option>Saturday October 29th</option>
<option>Monday October 31st</option>
</select>
The DateTime object’s diff() method tells you the difference between two dates. It returns a DateInterval object, which encapsulates the interval between the dates. Example 15-7 checks whether a given birthdate means someone is over 13 years old.
Example 15-7. Computing a date interval
$now = new DateTime();
$birthdate = new DateTime(‘1990-05-12’);
$diff = $birthdate->diff($now);
if (($diff->y > 13) && ($diff->invert == 0)) {
print “You are more than 13 years old.”;
} else {
print “Sorry, too young.”;
}
In Example 15-7, the call to $birthdate->diff($now) returns a new DateInterval object. This object’s properties describe the interval between $birthdate and $now. The y property is the number of years and the invert property is 0 when the difference is a positive amount (the invert property would be 1 if $birthdate were after $now). The other properties are m (months), d (days in the month), h (hours), i (minutes), s (seconds), and days (total number of days between the two dates).
Source: Sklar David (2016), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.