Example date addition and subtraction method in PHP

  • 2021-07-16 01:58:55
  • OfStack

Almost all programmers who are engaged in program development encounter time processing problems, as is PHP development. Fortunately, PHP provides many functions about date and time. As long as these functions are used frequently and used together, practice makes perfect in date and time processing.

In this example we are going to talk about today, the demand is like this. Knowing a certain date and time,

For example: 2012-04-25 10:10:00

I want to add 5 months to this datetime and return the processed date

Results: 2012-04-25 10:10:00 plus 5 months equals 2012-09-25 10:10:00

This requirement seems simple, but it is still a bit tricky, because PHP does not directly provide date and time in the format of yyyy-mm-dd hh: ii: ss for addition and subtraction, so it can only be realized by timestamp. Time stamp is the standard format of program conversion, which is accurate to seconds. PHP can convert various date formats into timestamps and timestamps back to various date formats. Combining these two characteristics, we roughly realize three steps: first convert the original time into timestamps, then add and subtract, and finally convert back to date formats.

Of course, this is the implementation principle, combined with PHP function date () and strtotime () two functions to achieve roughly the same meaning, please see the example code


<?php
/**
 * PHP Date addition and subtraction method in
 * Qiongtai old house
 */
// No. 1 1 Step, suppose there is 1 Time
$a = '2012-04-25 10:10:00';
 
// No. 1 2 Step to get the timestamp of this date
$a_time = strtotime($a);
 
// No. 1 3 Step, get plus 5 Timestamp after 6 months
$b_time = strtotime('+5 Month',$a_time);
 
// No. 1 4 Section to convert the timestamp back to date format
$b = date('Y-m-d H:i:s',$b_time);
echo ' This is added 5 Date after 6 months '.$b;
 
// If you think the above code is too long, you can also 1 That's done
$b = date('Y-m-d H:i:s',strtotime('+'.$time.' Month',strtotime($a)));
echo ' This is added 5 Date after 6 months '.$b;
?>

The use of the date () function and the strtotime () function is not covered in detail here. Need children's shoes can see my previous related function introduction articles or to php. net to see the manual can be.


Related articles: