PHP calculates the function of two dates apart, how many months, how many days

Source: Internet
Author: User
When you do a project like OA, you may run into a situation that calculates the length of an employee's seniority, which is not enough to be accurate to the year or to the month, and to share a function that is accurate to how many days. Can be shown in this form similar to 1 years 25 days apart.

/*

*function: Calculate how many years, how many months, and how many days are two dates apart
*param string $date 1[format: 2011-11-5]
*param string $date 2[format: 2012-12-01]
*return array Array (' Year ', ' Month ', ' Day ');
*/
function Diffdate ($date 1, $date 2) {
if (Strtotime ($date 1) >strtotime ($date 2)) {
$tmp = $date 2;
$date 2= $date 1;
$date 1= $tmp;
}
List ($Y 1, $m 1, $d 1) =explode ('-', $date 1);
List ($Y 2, $m 2, $d 2) =explode ('-', $date 2);
$Y = $Y 2-$Y 1;
$m = $m 2-$m 1;
$d = $d 2-$d 1;
if ($d <0) {
$d + = (int) date (' t ', Strtotime ("-1 month $date 2"));
$m--;
}
if ($m <0) {
$m +=12;
$y--;
}
Return Array (' year ' = = $Y, ' month ' = = $m, ' Day ' + $d);

}

The function uses the following method: Echo '

;p Rint_r (diffdate (' 2012-12-1 ', ' 2011-11-5 '));//These two parameters are not ordered in 

The results are printed as follows:

Array

(
[year] + 1
[month] + 0
[Day] = +

)

The above results mean that the two dates are 1 years apart 26 days.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.