Masnad Nihit
Masnad Nihit

Reputation: 1996

php codeigniter getting number of months from 2 different dates

I am trying to get the number of months from two different dates. I am using codeigniter php, and I have seen in alot of places that the code I am using should work, but I am getting a error.

public function check($token){
if ($this->input->is_ajax_request()){
    $id = $this->myajax->getUserByAuth($token);
    if ($id){
        $this->load->model('user_profile');
        $result = $this->user_profile->check($id);

        $this->load->model('riskrating');
        //$this->riskrating->getRiskrateOfuser($id);
        $riskCategory ='4';
        $result['riskCategory']  = $riskCategory;


        $date1 = new DateTime($result['insertdate']);
        $date2 = new DateTime('now');
        $diff = $date1->diff($date2);
        $month = $diff->format('%m');
        if ($month > 6){
         return  $result['month'] = 'invalid';
        }else{
           return $result['month'] = 'valid';
        }

        $this->output->set_content_type('application/json');
        $this->output->set_output(json_encode($result));
    } else {
        $this->output->set_status_header('401', 'Could not identify the user!');
    }
} else {
    $this->output->set_status_header('400', 'Request not understood as an Ajax request!');
}

}

The $date1 has a value of '2016-08-19'. is it because that they are not different months? I thought if they are the same month it should just return zero. But how much I can see from debugging the error is in this line $diff = $date1->diff($date2);

Upvotes: 0

Views: 1744

Answers (4)

Virb
Virb

Reputation: 1578

As per your question, if you are only want to get number of months then just make the difference between two months.

$date1 = date('m',strtotime($var1->fieldname));
$date2 = date('m',strtotime($var2->fieldname));

$month_diff = $date1 - $date2;

Here, $var1 should be greater value than the $var2.

Upvotes: 1

Shibon
Shibon

Reputation: 1574

try this

$date1 = '2016-01-25';
  $date2 = '2016-06-20';

 $time_stamp1 = strtotime($date1);
$time_stamp2 = strtotime($date2);

$year1 = date('Y', $time_stamp1);
$year2 = date('Y', $time_stamp2);

$month1 = date('m', $time_stamp1);
$month2 = date('m', $time_stamp2); 

echo $diff = (($year2 - $year1) * 12) + ($month2 - $month1);

Upvotes: 3

Arun sankar
Arun sankar

Reputation: 114

You can simply use datetime diff and format for calculating difference.

$datetime1 = new DateTime('2009-10-11 12:12:00');
$datetime2 = new DateTime('2009-10-13 10:12:00');
$interval = $datetime1->diff($datetime2);
$month = $interval->format('%m');

Upvotes: 2

Tom Wright
Tom Wright

Reputation: 2861

You should be using the DateTime class. Try this:

$date1 = new DateTime($result['insertdate']);
$date2 = new DateTime('now');

$diff = $date1->diff($date2);

$diff should now be an instance of DateInterval.

Upvotes: 1

Related Questions