Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time Difference in PHP

I am trying to create an attendance system. Attendance System in PHP

On check out I call a function which updates attendance in database and calculate hours (Using Codeigniter)

public function updateAttendance($data,$id)
    {
    date_default_timezone_set('Asia/Karachi');
    $attendance=array(
        'check_in'=> $data['check_in'],
        'check_out'=> $data['check_out']
    );
    $this->db->WHERE('id',$id)->update('attendance',$attendance);
    $this->db->query('UPDATE attendance SET hours=(HOUR(TIMEDIFF(check_out,check_in))-1) WHERE DATE(date)=\''.date('Y-m-d').'\' and employee_id='.$id);
    return true;
}

I fetch my attendance by employee Id and render a view like this in employee's profile.

Employee Attendance

The problem is I am getting wrong calculation of hours, probably due to my query. Is there a fix by query or do I have to do keep time diff in time format and then add all of them at the end of month and then get hours out of it.

like image 412
Malik Mudassar Avatar asked Jan 08 '17 05:01

Malik Mudassar


People also ask

How can I get time difference in PHP?

You can use strtotime() function to get the time difference between two dates (DateTimes) in minutes using PHP.

How do I count hours in PHP?

$day1 = "2014-01-26 11:30:00"; $day1 = strtotime($day1); $day2 = "2014-01-26 12:30:00"; $day2 = strtotime($day2); $diffHours = round(($day2 - $day1) / 3600); echo $diffHours; ?>

How can calculate date difference in days in PHP?

The date_diff() function is an inbuilt function in PHP that is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure.


2 Answers

You can try this one...

$to_time = strtotime("2008-12-13 10:42:00");
$from_time = strtotime("2008-12-13 10:21:00");
echo round(abs($to_time - $from_time) / 60,2). " minute";
like image 62
Pravin Durugkar Avatar answered Oct 29 '22 17:10

Pravin Durugkar


i think its better to use this function:

$ MY_TIME = strtotime('2017-01-04 23:12');

this line of code return this digits: 1483571520

you can doing operation on them

and you can return them to date format for saving in database with this function:

date('y-m-d H:i',$MY_TIME);
like image 31
nima Avatar answered Oct 29 '22 17:10

nima