如何在PHP中计算时差? [重复]

问题描述 投票:0回答:6

我必须计算日期时间差,如何在 PHP 中做到这一点?我需要准确的小时、分钟和秒。有人有这个脚本吗?

php date
6个回答
31
投票

使用 PHP 的 DateTime 类diff() 方法,如下所示:-

$lastWeek = new DateTime('last thursday');
$now = new DateTime();
var_dump($now->diff($lastWeek, true));

这将为您提供一个 DateInterval 对象:-

object(DateInterval)[48]
  public 'y' => int 0
  public 'm' => int 0
  public 'd' => int 2
  public 'h' => int 11
  public 'i' => int 34
  public 's' => int 41
  public 'invert' => int 0
  public 'days' => int 2

从中检索您想要的值是微不足道的。


10
投票

这应该可行,只需将时间差异中的时间替换为任务开始时间和当前时间或任务结束时间即可。对于连续计数器,开始时间将存储在数据库中,或者对于任务的经过时间,结束时间也将存储在数据库中

function timeDiff($firstTime,$lastTime){
   // convert to unix timestamps
   $firstTime=strtotime($firstTime);
   $lastTime=strtotime($lastTime);

   // perform subtraction to get the difference (in seconds) between times
   $timeDiff=$lastTime-$firstTime;

   // return the difference
   return $timeDiff;
}

//Usage :
$difference = timeDiff("2002-03-16 10:00:00",date("Y-m-d H:i:s"));
$years = abs(floor($difference / 31536000));
$days = abs(floor(($difference-($years * 31536000))/86400));
$hours = abs(floor(($difference-($years * 31536000)-($days * 86400))/3600));
$mins = abs(floor(($difference-($years * 31536000)-($days * 86400)-($hours * 3600))/60));#floor($difference / 60);
echo "<p>Time Passed: " . $years . " Years, " . $days . " Days, " . $hours . " Hours, " . $mins . " Minutes.</p>";

9
投票

检查这个..这应该有效

<?php

function timeDiff($firstTime,$lastTime)
{

// convert to unix timestamps
$firstTime=strtotime($firstTime);
$lastTime=strtotime($lastTime);

// perform subtraction to get the difference (in seconds) between times
$timeDiff=$lastTime-$firstTime;

// return the difference
return $timeDiff;
}

//Usage :
echo timeDiff("2002-04-16 10:00:00","2002-03-16 18:56:32");

?> 

3
投票

对于类似的事情,请使用内置的 int time() 函数。

  • 存储
    time();
    的值,例如
    1274467343
    这是自
  • 以来的秒数
  • 当需要时检索值 并将其分配给
    $erlierTime
  • 再次将
    time()
    分配给后者 停止你想要的时间,让我们 就叫它
    $latterTime

所以现在你有类似

$erlierTime
$latterTime
的东西。

现在只需执行

$latterTime - $erlierTime
即可获得以秒为单位的差异,然后进行除法以获得过去的分钟数、过去的小时数等。


为了让我或任何人给你一个完整的脚本,你需要告诉我们你的环境是什么样的,以及你正在使用 mysql、sqlite 等......还需要知道如何触发该计时器。


0
投票

最好的解决方案是使用您的自定义代码,php中有很多内置函数可以让您轻松做到这一点。 日期时间时间

  1. 首先使用 strtotime 函数将任何日期从“Y-m-d H:i:s”格式转换为 Linux 时间戳。
  2. 进行计算并使用 time 获取当前时间戳(如果适用)。
  3. 使用 date 函数将计算出的时间戳转换为日期。

0
投票

您必须通过 strtotime 转换开始日期时间和结束时间。

之后用结束时间减去开始时间。

之后将差异传递给您需要的日期或时间格式...

这样您将获得两个日期之间的确切差异。

© www.soinside.com 2019 - 2024. All rights reserved.