将日期差异的结果保存在 PHP

Save the results of the date difference on PHP

如何将日期差的结果保存到数据库中?

    public function save(){
       $item      = $this->input->post('item');
       $date_in   = $this->input->post('date_in'); //date in
       $date_out  = $this->input->post('date_out'); // date out
       $hasil = $date_in->diff($date_out); 
       //echo $hasil->format('%a'); I will save these results to the database


    $data_insert = array(
        'item'             => $item,
        'date_in'          => $date_in,
        'date_out'         => $date_out,
        'selisih'          => $hasil
      );
//url save
}

如果你想有所不同,你可以通过 Carbon 轻松获得它,使用 diffInDays 示例代码:

$first = \Carbon\Carbon::createFromFormat('Y-m-d H:s:i', $date_in);
$second = \Carbon\Carbon::createFromFormat('Y-m-d H:s:i', $date_out);
$diff_in_days = $second->diffInDays($first);

或者不使用 Carbon 获取它:

$first = new DateTime($date_in);
$second = new DateTime($date_out);
$interval = $first->diff($second);

字符串没有方法diffdiffDateTime的方法,需要把字符串改成DateTime。

它会 return DateInterval object, you can get the total days by format('%a') 并插入数据库;

$hasil = (new DateTime($date_in))->diff(new DateTime($date_out));
$hasil = $hasil->format('%a');

$data_insert = array(
  'item'             => $item,
  'date_in'          => $date_in,
  'date_out'         => $date_out,
  'selisih'          => $hasil
);
$this->db->insert('mytable', $data_insert);