【问题标题】:Calculate the date difference in the given format in PHP4在 PHP4 中计算给定格式的日期差异
【发布时间】:2011-01-22 20:42:22
【问题描述】:

我需要一个 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) 

如果您需要更多详细信息,请告诉我。 提前致谢。

【问题讨论】:

  • 好像我真的需要这么说,但你真的需要先升级你的PHP版本。 PHP4 已经有一段时间不被支持了...
  • 是的,实际上我同意你的观点,在 php5 中有很好的功能,但我只需要在 php4 中执行此操作,因为我还必须支持 php4。

标签: php date timestamp php4


【解决方案1】:

让我们尝试这样的事情。

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

【讨论】:

  • 顺便说一句,我不太确定 PHP4 中是否有静态变量。如果没有,只需删除静态关键字:)
  • PHP 说“为了与 PHP 4 兼容,如果没有使用可见性声明,则属性或方法将被视为已声明为公共。”
  • 感谢您的回复。代码在所有测试用例中运行良好。
【解决方案2】:

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

希望这会有所帮助。
——阿尔贝托

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 2012-04-21
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    相关资源
    最近更新 更多