Reputation: 11
I am trying to make a time track system using php in which i have two buttons like clock in and clock out . I am storing the clock in time and clock out time in session variables. Now my requirement is to calculate the difference between the clock in time and clock out time. If you have a clear idea about calculating the difference between the times share the thoughts with me
<?php
if(isset($_POST['start']))
{
date_default_timezone_set('Asia/Calcutta');
$time_start=date("Y-m-d h:i:s A");
setcookie('start',$time_start,time()+(36400)*3,'/');
echo "time start now ".$time_start."<br>";
}
if(isset($_POST['end']))
{
date_default_timezone_set('Asia/Calcutta');
$time_end=date("Y-m-d h:i:s A");
setcookie('end',$time_end,time()+(36400)*3,'/');
echo "time was ended".$time_end."<br>";
?>
<html>
<body>
<form method="POST">
<input type="submit" name="start" value="Start">
<br><br>
<input type="submit" name="end" value="End">
</form>
</body>
</html>
Upvotes: 0
Views: 619
Reputation: 33813
The DateTime
class has a variety of methods which can make working with dates quite simple. Perhaps the following will give an idea of how you could achieve your goal.
$format='Y-m-d H:i:s';
$timezone=new DateTimeZone('Asia/Calcutta');
$clockin = new DateTime( date( $format, strtotime( $_COOKIE['start'] ) ),$timezone );
$clockout= new DateTime( date( $format, strtotime( $_COOKIE['end'] ) ), $timezone );
$diff=$clockout->diff( $clockin );
echo $diff->format('%h hours %i minutes %s seconds');
Further reading can be found here
To fully test I wrote this quickly - it appears to work just fine!
<?php
$cs='shift_start';
$cf='shift_end';
date_default_timezone_set('Europe/London');
if( isset( $_POST['start'] ) ){
setcookie( $cs, date("Y-m-d h:i:s A"), time()+(36400)*3,'/');
}
if( isset( $_POST['end'] ) ){
setcookie( $cf, date("Y-m-d h:i:s A"), time()+(36400)*3,'/');
}
?>
<!doctype html>
<html>
<head>
<title>Set cookies and get time difference</title>
</head>
<body>
<form method="post">
<input type="submit" name="start" value="Clock-In">
<input type="submit" name="end" value="Clock-Out">
<br /><br />
<input type='submit' name='show' value='Show duration' />
</form>
<?php
if( isset( $_POST['show'] ) ){
$format='Y-m-d H:i:s';
$timezone=new DateTimeZone('Europe/London');
$clockin = new DateTime( date( $format, strtotime( $_COOKIE[ $cs ] ) ),$timezone );
$clockout= new DateTime( date( $format, strtotime( $_COOKIE[ $cf ] ) ), $timezone );
$diff=$clockout->diff( $clockin );
echo $diff->format('%h hours %i minutes %s seconds');
}
?>
</body>
</html>
Upvotes: 1