我想工作的日期是第一次,我做了一些事与Flash,但它是不同的。

我有两个不同的日期,我想看看在几小时或几天内与他们不同,我发现太多的例子,但不是我寻找热塑成型为:

<?php
    $now_date = strtotime (date ('Y-m-d H:i:s')); // the current date 
    $key_date = strtotime (date ("2009-11-21 14:08:42"));
    print date ($now_date - $key_date);
    // it returns an integer like 5813, 5814, 5815, etc... (I presume they are seconds) 
?>

我怎样才能将其转换为小时或天?

有帮助吗?

解决方案

好了,你可以随时使用date_diff,但仅适用于PHP 5.3.0 +

在替代方案是数学。

  

如何呢[秒]转换成小时或至几天?

有每分钟60秒,这意味着有每小时3600秒。

$hours = $seconds/3600;

和,当然,如果你需要天...

$days = $hours/24;

其他提示

DateTime DIFF函数返回一个DateInterval对象。该对象包含有关差异variabeles的。您可以查询天,时,分,秒,就像在上面的例子。

示例:

<?php 
 $dateObject = new DateTime(); // No arguments means 'now'
 $otherDateObject = new DateTime('2008-08-14 03:14:15');
 $diffObject = $dateObject->diff($otherDateObject)); 
 echo "Days of difference: ". $diffObject->days; 
?>

请参阅手动有关 DateTime

<强>不幸的是,它是一个PHP 5.3>唯一特征。

如果你没有PHP5.3你可以使用从用户态这种方法(从WebDeveloper.com 截取)

function date_time_diff($start, $end, $date_only = true)  // $start and $end as timestamps
{
    if ($start < $end) {
        list($end, $start) = array($start, $end);
    }
    $result = array('years' => 0, 'months' => 0, 'days' => 0);
    if (!$date_only) {
        $result = array_merge($result, array('hours' => 0, 'minutes' => 0, 'seconds' => 0));
    }
    foreach ($result as $period => $value) {
        while (($start = strtotime('-1 ' . $period, $start)) >= $end) {
            $result[$period]++;
        }
        $start = strtotime('+1 ' . $period, $start);
    }
    return $result;
}

$date_1 = strtotime('2005-07-31');
$date_2 = time();
$diff = date_time_diff($date_1, $date_2);
foreach ($diff as $key => $val) {
    echo $val . ' ' . $key . ' ';
}

// Displays:
// 3 years 4 months 11 days 

TheGrandWazoo提及为PHP 5.3的方法>。对于较低的版本,你可以devide在一天中的秒数两个日期之间的秒数找到的天数。

有关天,你做的:

$days = floor(($now_date - $key_date) / (60 * 60 * 24))

如果你想知道多少个小时仍然留下,你可以使用模运算符(%)

$hours = floor((($now_date - $key_date) % * (60 * 60 * 24)) / 60 * 60)
<?php
    $now_date = strtotime (date ('Y-m-d H:i:s')); // the current date 
    $key_date = strtotime (date ("2009-11-21 14:08:42"));
    $diff = $now_date - $key_date;
    $days    = floor($diff/(60*60*24));
    $hours   = floor(($diff-($days*60*60*24))/(60*60));
    print $days." ".$hours." difference";
?>

我更喜欢使用历元/ UNIX时间增量。时间,以秒表示,因此可以通过3600小时和除法很快除以24 * 3600 = 86400天。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top