PHP Dates and Times
Adding to or Subtracting from a Date
Problem
You need to add or subtract an interval from a date.Solution
Apply a DateInterval object to a DateTime object with either the DateTime::add() or DateTime::sub() method, as shown in example.Example Adding and subtracting a date interval
$birthday = new DateTime('March 10, 1975');
// When is 40 weeks before $birthday?
$human_gestation = new DateInterval('P40W');
$birthday->sub($human_gestation);
print $birthday->format(DateTime::RFC850);
print "\n";
// What if it was an elephant, not a human?
$elephant_gestation = new DateInterval('P616D');
$birthday->add($elephant_gestation);
print $birthday->format(DateTime::RFC850);
Discussion
The add() and sub() methods of DateTime modify the DateTime method they are called on by whatever amount is specified in the interval. The average human gestation time is 40 weeks, so an interval of P40W walks back the birthday to 40 weeks earlier, approximating conception time.
An elephant, on the other hand, has an average gestation timeof 616 days. So, adding an interval of P616D to that conception time produces the expected due date of an elephant conceived at the same time as the human.
A DateTime object’s modify() method accepts, instead of a DateInterval object, a string that strtotime() understands. This provides an easy way to find relative dates like “next Tuesday” from a given object.
For example, election day in the United States is the Tuesday after the first Monday in November. (That is, the first Tuesday of November, unless that’s the first of the month, in which case it’s the following Tuesday.) With DateTime::modify() you can find the date of election day as follows:
$year = 2016;
$when = new DateTime("November 1, $year");
if ($when->format('D') != 'Mon') {
$when->modify("next Monday");
}
$when->modify("next Tuesday");
print "In $year, US election day is on the " .
$when->format('jS') . ' day of November.';
The format character D produces the day of the week. So if the first day of November is not a Monday, the call to $when->modify("next Monday") advances the DateTime object to the following Monday. Then, the subsequent call to modify() finds the first Tuesday after that.
No comments:
Post a Comment