格式为php的时间计算问题

时间:2017-09-02 00:02:37

标签: php time

我无法计算工作小时数。 我们从在这种情况下以字符串开头的时间开始($ time)。 然后我们将时间更改为00:00:00并将结果存储为新变量($ newtime)。 然后我们需要计算$ time和$ newtime之间的差异,但是有一个我不完全理解的格式问题。有人会帮忙吗?

$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>";

2 个答案:

答案 0 :(得分:3)

您正在使用DateTime对象减去时间戳,因此它会尝试将DateTime对象转换为int,而不能转换为<?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>"; 。您需要获取DateTime对象的时间戳,以减去两个整数:

#include <cstdio>

答案 1 :(得分:1)

你正在混合类型(试图将对象转换为int)...也许你没有意识到你正在犯的错误,因为你已经禁用了错误。

请使用,Datetime类为您带来的方法:

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

您可以通过以下两种方式实现:

$newtime->getTimestamp()

或使用此:

date_timestamp_get($newtime)

这样:

$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>";

请免费使用:http://sandbox.onlinephpfunctions.com/code/f78c993f709a67ac2770d78bb809e68e3a679707