簡體   English   中英

用PHP4計算給定格式的日期差

[英]Calculate the date difference in the given format in 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) 

如果您需要更多詳細信息,請告訴我。 提前致謝。

使用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);

希望這可以幫助。
—阿爾貝托

讓我們嘗試這樣的事情。

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天。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM