Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.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 - Fatal编程技术网

Php 将小时转换为时间戳

Php 将小时转换为时间戳,php,Php,要将日期转换为时间戳,我通常会这样做-strotime(“2018-05-17 05:04:34”),但现在,我只想将小时(无日期)转换为时间戳,例如02:00:00。我该如何做 我之所以需要它是为了比较某个时间是否大于指定的小时。这就是我正在做的: $reported = strtotime("2018-05-17 05:04:34"); $respons = strtotime("2018-05-17 17:04:34); $response_time = $respons - $repor

要将日期转换为时间戳,我通常会这样做-strotime(“2018-05-17 05:04:34”),但现在,我只想将小时(无日期)转换为时间戳,例如02:00:00。我该如何做

我之所以需要它是为了比较某个时间是否大于指定的小时。这就是我正在做的:

$reported = strtotime("2018-05-17 05:04:34");
$respons = strtotime("2018-05-17 17:04:34);
$response_time = $respons - $reported;

我想检查$response\u time是否大于1小时。

我喜欢DateTime类,请尝试一下:

<?php

$reported = new DateTime('2018-05-17 05:04:34');
$reported->modify('+2 hours');
$now = new DateTime();

echo $now < $reported ? 'less than 2 hours' : 'more than 2 hours';

我相信只有我正确理解了你的问题

我只想将小时(无日期)转换为时间戳,例如02:00:00

这里没有日期组件

好的,我假设它们的日期相同。如果是这种情况,只需在两者前面附加任意日期即可使
strotime()
函数工作:

$start = "05:04:34";
$end = "17:04:34";
$reported = strtotime("2018-05-17 " . $start);
$respons = strtotime("2018-05-17 " . $end);
$response_time = $respons - $reported;
if ($response_time > 3600)
  echo "More than hour!";
else
  echo "Less than hour!";
注意:如果开始时间为17:00,结束时间为08:00,则此操作不起作用,该时间发生在第二天。您必须确保如果开始时间大于结束时间,则必须在结束时间的基础上再增加一天


DateTime::diff
,它可能满足您的需要

在你的情况下应该是这样的

$datetime1 = new DateTime("2018-05-17 05:04:34");
$datetime2 = new DateTime("2018-05-17 17:04:34);
$interval = $datetime1->diff($datetime2);
echo $interval->format('H hours');

strotime解析没有日期的时间没有问题。
不需要伪造一个日期,它会回来,并用夏令时咬你。
我还添加了一个检查,查看开始/结束是否“反转”

$start=“2018-05-17 05:04:34”;
$end=“2018-05-17 17:04:34”;
//请注意,它是有意反转的
$diff=strottime(substr($start,11))-strottime(substr($end,11));
//如果计算结果相反,则以秒为单位添加一天
若有($3600){
回声“超过一小时”;
}否则{
回声“不到一小时”;
}

它们的日期是否相同?使用substr并删除字符串的前11个字符。@安德烈因为问题是当只有时间成分而没有日期成分时,如何进行计算。这是一样的。一小时是3600秒。问题是当只有时间成分而没有日期成分时,如何进行计算。你提到没有日期在我的评论中允许部分内容,但你也可以这样做。你在附加任意内容dates@delboy1978uk那么?只有在
strotime()之后
函数正常工作?没有日期组件它无法工作。OP只需要一个代码,它必须在没有日期组件的情况下比较两次。那么为什么要批评我的解决方案呢?它更重要elegant@delboy1978uk不,我不是批评你的。你完全偏离了OP想要的。OP有两次。开始和结束(我相信)他们想得到不同,但没有日期。
$start= "2018-05-17 05:04:34";
$end = "2018-05-17 17:04:34";

//Note that it's intentionally reversed
$diff = strtotime(substr($start,11))-strtotime(substr($end,11));

//If the calculation was reversed add one day in seconds
if($diff <0) $diff += 86400;

If($diff >3600){
    Echo "more than one hour";
}Else{
    Echo "less than one hour";
}