Jeff Sayers
Jeff Sayers

Reputation: 127

time calculation issue with format php

I'm having trouble calculating the number of hours worked. We start with a time which starts as a string in this case ($time). Then we change the time to 00:00:00 and store the result as a new variable ($newtime). Then we need to calculate the difference between $time and $newtime but there is a formatting issue which I do not fully understand. Would anyone help?

$time = "2017-09-01 11:00:00"; //must start as a string like this
$newtime = new DateTime($time);
$newtime->setTime(00, 00,00); //change time to 00:00:00
$worktime = round((strtotime($time) - $newtime)/3600, 2);
echo "Hours Worked: " . $worktime . "<br>";

Upvotes: 1

Views: 34

Answers (2)

z3nth10n
z3nth10n

Reputation: 2461

You are mixing types (trying to cast object to int)... And maybe you didn't realize about the error you are making because you have disabled errors.

Please use, the method that Datetime class brings to you:

http://php.net/manual/es/datetime.gettimestamp.php

You can do it in both ways:

$newtime->getTimestamp()

or by using this:

date_timestamp_get($newtime)

As this:

$time = "2017-09-01 11:00:00"; //must start as a string like this
$newtime = new DateTime($time);
$newtime->setTime(00, 00,00); //change time to 00:00:00
$worktime = round((strtotime($time) - date_timestamp_get($newtime))/3600, 2);
echo "Hours Worked: " . $worktime . "<br>";

Please, be free of using this: http://sandbox.onlinephpfunctions.com/code/f78c993f709a67ac2770d78bb809e68e3a679707

Upvotes: 1

ishegg
ishegg

Reputation: 9957

You're subtracting a timestamp with a DateTime object, so it tries to convert the DateTime object to an int, which it can't. You need to get the timestamp for the DateTime object, to subtract two ints:

<?php
$time = "2017-09-01 11:00:00"; //must start as a string like this
$newtime = new DateTime($time);
$newtime->setTime(00, 00,00); //change time to 00:00:00
$worktime = round((strtotime($time) - $newtime->getTimestamp())/3600, 2); // notice the $newtime->getTimestamp() call
echo "Hours Worked: " . $worktime . "<br>";

Upvotes: 3

Related Questions