Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中将字符串转换为时间_Php_Time - Fatal编程技术网

在PHP中将字符串转换为时间

在PHP中将字符串转换为时间,php,time,Php,Time,我从数据库中获取字符串数据 数据格式如下: 07:00:00.0000000 意思是早上7点。 如何将此字符串转换为日期类型以进行比较。 因此,我可以得到2个数据。比如 Start: 07:00:00.0000000 End: 16:30:00.0000000 经过时间比较后,我可以得到类似9.3的答案。您可以使用strotime: $start = strtotime("07:00:00.0000000"); $end = strtotime("16:30:00.0000000");

我从数据库中获取字符串数据 数据格式如下:

07:00:00.0000000
意思是早上7点。 如何将此字符串转换为日期类型以进行比较。 因此,我可以得到2个数据。比如

Start:
07:00:00.0000000
End:
16:30:00.0000000

经过时间比较后,我可以得到类似9.3的答案。

您可以使用
strotime

$start = strtotime("07:00:00.0000000");
$end   = strtotime("16:30:00.0000000");

$difference = $end - $start;
或使用DataTime对象:

$start = new DateTime("07:00:00.0000000");
$end   = new DateTime("16:30:00.0000000");

$interval   = $start->diff($end);
$difference = $end->getTimestamp() - $start->getTimestamp();
然后
echo
结果:

echo $difference;            // in seconds
echo $difference / 60;       // in minutes
echo $difference / 3600;     // in hours

echo $interval->format('%s') // in seconds

那就看你的喜好了。我还建议您看看这两种解决方案的性能。

您如何从中提取日期?您的意思是
日期和时间
?被否决的投票人能解释一下自己吗?我没有被否决,但我只能猜测这是因为您选择使用
strotime
而不是PHP的
DateTime
对象。我认为这里没有必要使用对象,但无论如何,我编辑了添加了一个使用DateTime对象的示例。提示:如果您使用DateTime对象,请查看diff函数:)@Duroth您是对的,在这种情况下,我进行了编辑以添加一个示例。