简体   繁体   中英

Difference between two PHP times as years, months and days for PHP version 5.2

Forward:

I've scanned through the existing questions/answers on this matter. This is not a duplicitous question; I cannot find a working solution from the accepted answers.

The main questions/answers I've reviewed can be found here: How to calculate the difference between two dates using PHP?

What I need:

A calucalation of the difference between two dates expressed as years, months and days that works with PHP version: 5.2 .

<?php
$current_date = date('d-M-Y');
$future_date = '2012-11-01';
?>

What I've tried:

  1. Most answers I find online don't seem to be exact in that they don't factor in leap years.
  2. This highly rated answer won't work because DateTime->diff() is php 5.3+.
  3. This accepted answer (ie the second block of code aimed at PHP 5.2) results in the following being parsed:

    Array ( [y] => 25 [m] => 11 [d] => 7 [h] => 3 [i] => 15 [s] => 19 [invert] => 0 [days] => 9473 ) Array ( [y] => 25 [m] => 11 [d] => 7 [h] => 3 [i] => 15 [s] => 19 [invert] => 1 [days] => 9473 )

I can't tell if I've incorrectly applied the code or it's simply a case of me not knowing how to manipulate the array.

您是否已在DateTime::diff()手册页上看到此注释?

I too was working on the same thing. This might Work! First you need to create dates.

$date1=date_create("2012-03-15");
$date2=date_create("2013-03-15");

Here's the manual for that! Then to find the difference between dates and printing the desired result use this!

$dif=date_diff($date1,$date2); //Will calculate the difference between two dates.
$days = $dif->days; //Days
$years = round($age/365); //Converting days to years and rounding them up.
$months = $difference/30; // Converting to months.
echo "Days =>".$days;
echo "Years =>".$years;
echo "Months =>".$months;

Now the answer that you'll get won't be precise because there is no method in this that is calculating leap years, but if precision is not what you are looking for then this will definitely work! I Know this question was asked a long time ago, but in my defense i just saw it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM