This article mainly introduces the example of the date addition and subtraction method in PHP, mainly used for the date () function and strtotime () function, for more information, see how almost all programmers engaged in program development encounter time processing problems. The same is true for PHP Development. Fortunately, PHP provides many date and time functions. As long as these functions are frequently used and used together, it makes perfect for date and time processing.
The requirement for this example is as follows. Know a date and time,
Example: 10:10:00
I want to add 5 months based on this date and return the processed date.
Result: 10:10:00 + 5 months equals 10:10:00
This requirement seems simple, but it is still a bit tricky, because PHP does not directly provide date time in the format of yyyy-mm-dd hh: ii: ss for addition and subtraction, so it can only be achieved through time stamps. The timestamp is the standard format for program conversion, accurate to seconds. PHP can convert multiple date formats to timestamps and convert timestamps back to various date formats. in combination with these two features, we roughly implement three steps, first, convert the original time to the timestamp, add or subtract it, and finally convert it back to the date format.
Of course, this is the implementation principle. combining the date () and strtotime () functions of PHP functions, this is also the meaning. please refer to the instance code.
The code is as follows:
<? Php
/**
* Date addition and subtraction method in PHP
* Qiongtai old house
*/
// Step 1, assume there is a time
$ A = '2017-04-25 10:10:00 ';
// Step 2, obtain the timestamp of this date
$ A_time = strtotime ($ );
// Step 3: obtain the timestamp after adding five months
$ B _time = strtotime ('+ 5 month', $ a_time );
// Part 4: convert the timestamp back to the date format
$ B = date ('Y-m-d H: I: S', $ B _time );
Echo 'This is the date after adding five months '. $ B;
// If you think the above code is too long, you can do it in one line.
$ B = date ('Y-m-d H: I: S', strtotime ('+'. $ time. 'month', strtotime ($ )));
Echo 'This is the date after adding five months '. $ B;
?>
We will not detail the use of date () and strtotime () functions here. You can refer to my previous related function introduction articles or go to php.net to see the manual.