php - Returning months difference as integer

908

I am trying to return month difference as integer and call if to table column. My code:

function ETA($ArrivalDate, $pattern = 'mysql'){


$patterns = array(
    'eu'    => 'd/m/Y',
    'mysql' => 'Y-m-d',
    'us'    => 'm/d/Y',
);
    $CurrentDate = date("Y-m-d");

    $ArrivalDate = $variants_data['ArrivalDate'];

    $diff = $ArrivalDate->diff($CurrentDate);

    return $diff->y;

}

The I call it with

<td>'.$_GET['ETA'].'</td>

But there is nothing returned, what am I doing wrong here?

211

Answer

Solution:

You can get what you want in a simpler approach using the DateTime object in PHP:

function ETA($ArrivalDate){
    $currentDate = new DateTime();
    $arrivalDate = new DateTime($ArrivalDate);
    $interval    = $currentDate->diff($arrivalDate);
    return $interval->format('%m');
}

See working example: http://3v4l.org/UlPQo

If you don't pass in an appropriate format $ArrivalDate you will get an exception thrown, so you need to wrap the call in a Try/Catch.

See DateTime Interval Format for more on the return value.

967

Answer

Solution:

Try this simple one

<?php
  //for months
  $monthdiff=floor((abs(strtotime(date("d/m/Y")) - strtotime($ArrivalDate))/(60*60*24*30)));
  //for days
  $daydiff=floor((abs(strtotime(date("d/m/Y")) - strtotime($ArrivalDate))/(60*60*24)));

  ?>

People are also looking for solutions to the problem: php - URL modified from each click after change in htaccess

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.