在PHP4中计算给定格式的日期差异

时间:2011-01-22 20:42:22

标签: php date timestamp php4

我需要php4中的一个函数来计算提供日期格式的日期差异。 例如

$date1 = "2011-08-24 10:03:00";
$date2 = "2012-09-24 10:04:31";
$format1 = "Y W" ; //This format should return the difference in Year and week.
$format2 = "M D"; // This format should return the difference in Months and days.
// The format can be any combination of Year,Month,Day,Week,Hour,Minute,Second.

function ConvertDate($data1,$date2,$format) 

如果您需要更多详细信息,请与我们联系。 提前谢谢。

2 个答案:

答案 0 :(得分:3)

使用mktime获取日期的Unix时间戳。然后你得到的不同之处是:

$years = floor(($date2-$date1)/31536000);
$months = floor(($date2-$date1)/2628000);
$days = floor(($date2-$date1)/86400);
$hours = floor(($date2-$date1)/3600);
$minutes = floor(($date2-$date1)/60);
$seconds = ($date2-$date1);

希望这有帮助。
-Alberto

答案 1 :(得分:3)

让我们尝试这样的事情。

function ConvertDate($date1, $date2, $format)
{
    static $formatDefinitions = array(
        'Y' => 31536000,
        'M' => 2592000,
        'W' => 604800,
        'D' => 86400,
        'H' => 3600,
        'i' => 60,
        's' => 1
    );

    $ts1 = strtotime($date1);
    $ts2 = strtotime($date2);
    $delta = abs($ts1 - $ts2);

    $seconds = array();
    foreach ($formatDefinitions as $definition => $divider) {
        if (false !== strpos($format, $definition)) {
            $seconds[$definition] = floor($delta / $divider);
            $delta = $delta % $divider;
        }
    }

    return strtr($format, $seconds);
}

请记住,几个月和几年只是估计,因为你不能说“一个月有多少秒”(因为“月”可以是28到31天之间的任何时间)。我的功能将一个月计为30天。