如何获得两个时间戳之间的差异


How to get the difference between 2 timestamps?

我在这个项目中使用codeigniter 3.0.3。

我正在试着弄清楚两个时间戳(打卡和下班)之间的区别。

以下是尝试这样做的函数:

public function clock_user_out()
{
    $this->db->where('USER_EMAIL', $this->session->userdata('USER_EMAIL')) 

    $data = $this->db->get('clocked_in_users'); 
    $uemail = $data->row()->USER_EMAIL;
    $uclockin = $data->row()->USER_CLOCK_IN;
    $uclockout = date(('Y-m-d H:i:s'));
    $uhours = $uclockout-$uclockin;
    $newdata['USER_EMAIL'] =  $uemail;
    $newdata['USER_CLOCK_IN'] = $uclockin;  

    $newdata['USER_CLOCK_OUT'] = $uclockout; 

    $newdata['USER_WORK_HOURS'] = $uhours;
    $this->db->insert('user_hours',$newdata);

    $this->db->where('USER_EMAIL', $this->session->userdata('USER_EMAIL'));     


    $this->db->delete('clocked_in_users'); 
}

我相信错误是当我从$uclockout中减去$uclockin得到变量$uhours时。

我正在处理的表中有5列。

  1. ID[int]
  2. USER_EMAIL[varchar]
  3. USER_CLOCK_IN[时间戳]
  4. USER_CLOCK_OUT[时间戳]
  5. USER_WORK_HOURS[时间]

现在,对于我测试的那个,这些就是结果。

  • USER_CLOCK_IN=2015-12-31 07:37:59
  • USER_CLOCK_OUT=2015-12-31 07:38:07

但是USER_WORK_ HOURS的结果是00:20:15。这对我来说没有意义。它看起来唯一像是在2015年,并将其分解为数据库中的TIME格式?

事情就是这样吗?我用错那一栏的格式了吗?

做这件事的正确方法是什么?

提前谢谢。

编辑:多亏了Ashok Chitroda和Jorge Torres,问题得到了解决

$uhours = $uclockout-$uclockin;

$uhours = date('H:i:s' , (strtotime(date('Y-m-d 00:00:00'))+ strtotime($uclockout) - strtotime($clockin) ));

而且我把一个变量拼写错了。

感谢大家

更换

$uhours = $uclockout-$clockin;

$uhours = date('H:i:s' , (strtotime(date('Y-m-d 00:00:00'))+ strtotime($uclockout) - strtotime($clockin) ));

您是否在减法中使用了错误的变量?

$uclockin = $data->row()->USER_CLOCK_IN;
$uclockout = date(('Y-m-d H:i:s'));
$uhours = $uclockout-$clockin;

注意$uclockin与$clockin

在查询中使用时间戳diff(UNIT、FIRST TIMESTAMP、SECOND TIMESTAMP)。点击此链接

您可以像这样使用

$to_time = $clockin;
$from_time =$uclockout;
$a= round(abs($to_time - $from_time) / 60);
echo ($a/60).' Hours';

如果您的$clockin不在时间戳中,请将日期转换为时间戳比如

$to_time = strtotime("2008-12-13 09:42:00");
$from_time = strtotime("2008-12-13 11:42:00");
$a= round(abs($to_time - $from_time) / 60);
echo ($a/60).' Hours';