DateTime diff在Wordpress页面中无法正常工作

时间:2012-01-06 14:42:07

标签: php wordpress datetime diff

全部, 我有以下PHP代码来确定我的Wordpress页面上两个日期相隔多少年:

<?php
$date1 = new DateTime("2003-03-24");
$current_date = new DateTime(date("Y-m-d"));
$interval = $date1->diff($current_date);
echo $interval->y;
?>

我为Wordpress安装了Exec-PHP插件以正确显示。但是,当我尝试显示我的页面时,我收到以下错误:

  

致命错误:调用未定义的方法DateTime :: diff()   /home/person/test.website.com/wp-content/plugins/exec-php/includes/runtime.php(42)   :eval()&#39; d代码在第7行

如何让它正常工作?谢谢!

2 个答案:

答案 0 :(得分:1)

正如manual中所述,DateTime::Diff(以及所有DateInterval函数)仅在PHP&gt; = 5.3.0中可用。

您需要安装该版本,或找到使用另一组功能的变通方法。 Here是如何使用旧的基于时间戳的日期函数执行此操作的示例。

答案 1 :(得分:1)

我回忆起这个问题:How to calculate the difference between two dates using PHP?

通过一些小的调整,它看起来像这样:

function convert_number($number) { 
    $Gn = floor($number / 1000000);  /* Millions (giga) */ 
    $number -= $Gn * 1000000; 
    $kn = floor($number / 1000);     /* Thousands (kilo) */ 
    $number -= $kn * 1000; 
    $Hn = floor($number / 100);      /* Hundreds (hecto) */ 
    $number -= $Hn * 100; 
    $Dn = floor($number / 10);       /* Tens (deca) */ 
    $n = $number % 10;               /* Ones */ 

    $res = ""; 

    if ($Gn)
        $res .= convert_number($Gn) . " Million"; 
    if ($kn)    { 
        $res .= (empty($res) ? "" : " ") . 
        convert_number($kn) . " Thousand"; 
    } 

    if ($Hn) { 
        $res .= (empty($res) ? "" : " ") . 
        convert_number($Hn) . " Hundred"; 
    } 

    $ones = array("", "One", "Two", "Three", "Four", "Five", "Six","Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen","Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen","Nineteen"); 
    $tens = array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty","Seventy", "Eigthy", "Ninety"); 

    if ($Dn || $n)  { 
        if (!empty($res))
            $res .= " and "; 

        if ($Dn < 2) 
        $res .= $ones[$Dn * 10 + $n]; 
        else { 
            $res .= $tens[$Dn]; 

            if ($n) 

            $res .= "-" . $ones[$n]; 
        } 
    } 

    if (empty($res)) 
        $res = "zero"; 

    return $res; 
} 

function yearsFromNow ($date) {
    return convert_number(floor(abs(strtotime($date) - strtotime(date("Y-m-d"))) / (365*60*60*24)));
}

echo yearsFromNow("2007-03-24");
echo yearsFromNow("2009-06-26");

输出:

4
2

从此网站修改的字母数字功能:http://www.phpro.org/examples/Convert-Numbers-to-Words.html