开发者

PHP - How to count how many months from a specific date

How can I count the number of months from the following two dates below using the Procedural style method?

PHP code.

$dele开发者_Go百科te_date = "2000-01-12 08:02:39";
$current_date = date('Y-m-d H:i:s'); //current date


You're looking for DateTime::diff?

$delete_date = "2000-01-12 08:02:39";
$date_format = 'Y-m-d H:i:s';
$current_date = date($date_format);
$diff = date_diff(date_create_from_format($date_format, $delete_date), date_create());
$months = $diff->m;

Something along the lines of that.


Using DateTime you will get the total months this way:

$d1 = new DateTime("2000-01-12 08:02:39");
$d2 = new DateTime();
$d3 = $d1->diff($d2);
$months = ($d3->y*12)+$d3->m;

You would still need to handle the leftover days $d3->d ... but that depends on your needs.


$delete_date = "2000-01-12 08:02:39";
$current_date = date('Y-m-d H:i:s'); //current date

$diff = strtotime($current_date) - strtotime($delete_date);
$months = floor(floatval($diff) / (60 * 60 * 24 * 365 / 12));
echo $months . "\n";


is this what you looking for?

$delete_date = "2000-01-12 08:02:39";
$current_date = date('Y-m-d H:i:s'); //current date

// convert date to int
$delete_date = strtotime($delete_date);
$current_date = strtotime($current_date);

// calculate it
$diff = $delete_date - $current_date;

// convert int to time
$conv_diff = date('format', $diff);


Try this, it is easy, maybe not enogh chick, but very effective.

function calculateMonthsBetweenDates($fMonth, $fDay, $fYear, $tMonth, $tDay, $tYear)
{
    //Build datetime vars using month, day and year
    $dateFrom = mktime(0, 0, 0, $fMonth, $fDay, $fYear);
    $dateTo   = mktime(0, 0, 0, $tMonth, $tDay, $tYear);

    //Check dateTo is a later date than dateFrom.
    if($dateFrom<=$dateTo){
        $yearF  = date("Y", $dateFrom);
        $yearT  = date("Y", $dateTo);
        $monthF = date("m", $dateFrom);
        $monthT = date("m", $dateTo);

        //same year
        if ($yearF == $yearT)
            $months = ($monthT - $monthF);
        else{
        //different year
            $months = (12*($yearT-$yearF)-$monthF) + $monthT;
            }
        return $months;
        }
    else
       return false; //or -1
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜