Home  >  Article  >  Backend Development  >  Sample code for date addition and subtraction methods in php

Sample code for date addition and subtraction methods in php

怪我咯
怪我咯Original
2017-07-11 15:08:321292browse

Almost all programmers engaged in program development encounter time processing problems, and PHP development is the same. Fortunately, PHP provides a lot of date and time functions. As long as you use these functions frequently and in combination, practice makes perfect in date and time processing.

The requirements for the example we are going to talk about today are as follows. Knowing a certain date and time,

such as: 2017-07-11 10:10:00

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

Result: 2017-07-11 10:10:00 plus 5 months equals 2017-09-25 10:10:00

This requirement seems simple, but it is still a bit tricky , because PHP does not directly provide the date and time in the format of yyyy-mm-dd hh:ii:ss for addition and subtraction, so it can only be achieved through Timestamp. Timestamps are the standard format for program conversions and are accurate to seconds. PHP can convert multiple date formats into timestamps, and can convert timestamps back into various date formats. Combining these two features, we can roughly implement three steps. First, convert the original time into a timestamp, then add and subtract, and finally convert back to date format.

Of course, this is the implementation principle. The same meaning is roughly achieved by combining the PHP function date() and strtotime(). Please see the example code

The code is as follows:

<?php
/**
 * PHP里的日期加减方法
 * 琼台老屋
 */
// 第一步,假设有一个时间
$a = &#39;2012-04-25 10:10:00&#39;;
 
// 第二步,获得这个日期的时间戳
$a_time = strtotime($a);
 
// 第三步,获得加五个月后的时间戳
$b_time = strtotime(&#39;+5 Month&#39;,$a_time);
 
// 第四部,把时间戳转换回日期格式
$b = date(&#39;Y-m-d H:i:s&#39;,$b_time);
echo &#39;这是加了五个月后的日期&#39;.$b;
 
// 如果你觉得以上代码过长也可以一行搞定
$b = date(&#39;Y-m-d H:i:s&#39;,strtotime(&#39;+&#39;.$time.&#39; Month&#39;,strtotime($a)));
echo &#39;这是加了五个月后的日期&#39;.$b;
?>

The above is the detailed content of Sample code for date addition and subtraction methods in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn