繁体   English   中英

php codeigniter从2个不同的日期获取月数

[英]php codeigniter getting number of months from 2 different dates

我正在尝试从两个不同的日期获得月数。 我使用的是codeigniter php,在很多地方都可以看到我使用的代码可以正常工作,但是却出现了错误。

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!');
}

}

$date1的值为'2016-08-19'。 是因为他们没有不同的月份吗? 我以为如果是同一个月,它应该只返回零。 但是从调试错误中我可以看到多少在这行中$diff = $date1->diff($date2);

尝试这个

$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);

您可以简单地使用datetime diff和format来计算差异。

$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');

您应该使用DateTime类。 尝试这个:

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

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

$diff现在应该是DateInterval的实例。

根据您的问题,如果您只想获得月数,那么请区别两个月。

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

$month_diff = $date1 - $date2;

在这里, $var1值应大于$var2值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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