0

I am attempting to use my Duration in my database to automatically get the difference between two timestamps (LeaveFrom and Leaveto) that are in a different format in my code. I have two Post variables that are spaced so that the first shows date in sql format and the other shows time in sql format.It works so that they both show as timestamp for Leaveto and LeaveFrom in my database. I want the duration variable to calculate the difference between the $begindate and $enddate in hours while it is inserted into the database with the other variables. Is this possible? Can someone explain how?

if(isset($_POST['LeaveRequest'])) { // checking that form is submitted

    session_start();  //creating variables for form entries
    $Enum = $_POST['Employeenumber'];
    $fullname = $_POST['Leavename'];
    $leavetype = $_POST['Leavetype'];
    $begindate = $_POST['LeaveFrom'].' '.$_POST['BeginTime'];
    $enddate = $_POST['Leaveto'].' '.$_POST['EndTime'];
    $duration = (I dont know!!)
    $unit = $_POST['Unit'];
    $leavereason = $_POST['LeaveReason'];
    $leavestatus = "Pending";
    $supervisor = $_POST['Supervisor'];

$sql = $con->query("INSERT INTO Leave_details 
(Employeenumber, Leavename, Leavetype, LeaveFrom, Leaveto, 
Duration, Unitpick, LeaveReason, LeaveStatus,  Supervisor)Values('{$Enum}', 
'{$fullname}', '{$leavetype}', '{$begindate}', '{$enddate}' ,'{$duration}',
'{$unit}' , '{$leavereason}', '{$leavestatus}', '{$supervisor}')");


     header('Location: Account.php');
alstonan25
  • 23
  • 8
  • look at http://stackoverflow.com/a/12382882/689579. It is in minutes not hours, but that is an easy conversion. – Sean Aug 27 '15 at 19:00
  • [Date Diff](http://www.w3schools.com/php/func_date_date_diff.asp) and [DateInterval](http://php.net/manual/en/class.dateinterval.php) should answer it? – Calvinthesneak Aug 27 '15 at 19:06

1 Answers1

0

You can use DateTime

(If you are using date format Y-m-d H:i:s or similar)

$begindate = new DateTime($_POST['LeaveFrom'].' '.$_POST['BeginTime']);
$enddate = new DateTime($_POST['Leaveto'].' '.$_POST['EndTime']);
$diff = $begindate->diff($enddate);
print_r($diff);

Output:

DateInterval Object
(
    [y] => 0
    [m] => 0
    [d] => 1
    [h] => 0
    [i] => 0
    [s] => 0
    [invert] => 1
    [days] => 1
)

So you can use:

$diff->h

Hope this helps.