开发者

Calculate the date difference in the given format in PHP4

开发者 https://www.devze.com 2023-02-05 23:43 出处:网络
I need a function in php4 that will calculate the date difference in the provided date format. eg. $date1 = \"2011-08-24 10:03:00\";

I need a function in php4 that will calculate the date difference in the provided date format. eg.

$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开发者_如何学JAVA difference in Months and days.
// The format can be any combination of Year,Month,Day,Week,Hour,Minute,Second.

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

Please let me know if you need any more details on this. Thanks in advance.


Let's try something like this.

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);
}

Just keep in mind that months and years are just estimated because you cannot say "how many seconds are a month" (because a "month" can be anything between 28 and 31 days). My function counts a month as 30 days.


Get Unix timestamps of your dates using mktime. Then you get the difference for:

$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);

Hope this helps.
—Alberto

0

精彩评论

暂无评论...
验证码 换一张
取 消