【问题标题】:Find two datetimes difference from database in codeigniter在codeigniter中查找与数据库的两个日期时间差异
【发布时间】:2018-02-26 04:21:47
【问题描述】:

我有 3 个输入表单,它们会将数据提交并保存到数据库,表单是:

  • wktu_down (此输入包含日期时间数据,例如 09/17/2017 9:58 PM 并将使用 Varchar 类型的数据存储到数据库中)
  • wktu_up (这是一样的)
  • time_report (这将包含计算结果 wktu_up - wktu_down)

我想当我点击 time_report 表单时,它会自动用结果填充数据,我不知道我应该使用 Javascript 还是不使用。

型号

function update_model($data, $id_report){
        $this->db->where('id_report',$id_report);
        $this->db->update('report', $data);
    }

    function get_data($id_report){
       $read= $this->db->query('select * from report where id_report='.$id_report);
        if($read->num_rows() > 0){
            foreach ($read->result() as $data){
                $hasil[] = array(
                    'id_report'=>$data->id_report,
                    'wktu_down'=>$data->wktu_down,
                    'wktu_up'=>$data->wktu_up,
                    'report_time'=>$data->report_time,
                );
            }
            return $result;
        }else{
            return false;
        }
    }

【问题讨论】:

  • 不要存储日期时间varchar类型数据改用datetime类型
  • 如果我使用日期时间类型,数据将是 0000-00-00 00:00:00
  • 插入前不只是正确格式化所选日期时间
  • 使用 datetime 类型,但是当您使用 PHP 接收数据时,将此日期重新格式化为 YYYY-mm-dd HH:ii:ss,这可能是所有 DBMS(如 MySQL)都支持的格式,也请使用 PHP 来计算两者之间的差异日期。请查看DateTime::diff
  • 哦,是的,我明白了,但是我如何实现这个功能?

标签: javascript php mysql codeigniter datetime


【解决方案1】:

对接收的数据使用日期时间类型,但您可能需要重新格式化日期值,尝试:

// I get the format for your example '09/17/2017 9:58 PM'
$wktu_down = DateTime::createFromFormat('d/m/Y h:i a', $this->input->post('wktu_down'));
// The var $wktu_down is a DateTime Object and you need use the method format()
echo $wktu_down->('Y-m-d H:i:s');

要获得两个日期之间的差异,请使用DateTime::diff,如下所示:

// First get the DateTime object of two dates
$wktu_down = DateTime::createFromFormat('d/m/Y h:i a', $this->input->post('wktu_down'));
$wktu_up = DateTime::createFromFormat('d/m/Y h:i a', $this->input->post('wktu_up'));
// Get the diff
$diff = $wktu_down->diff($wktu_up);
// Format the diff to days
echo $diff->format('%a days');

有可能以分钟、小时等方式获得差异。检查DateInterval::format

不要忘记 post() 方法的第二个参数,如果它包含任何 XSS attack 的值,则使用它来清理值。

$this->input->post('wktu_up', TRUE);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 2016-12-30
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    相关资源
    最近更新 更多