Smarty如何计算两个日期之间的天数差异

Smarty how to calculate days difference between two dates

如何计算两个日期之间的差异并在 SMARTY 模板引擎中找到天数?我知道逻辑部分应该完成 PHP 并将值分配给 SMARTY。但有时我们会遇到无论如何都必须反之亦然的情况。即使它违反了使用模板引擎的逻辑,我也必须在 smarty 中计算这种差异。

这是我的代码:

function returnReferrals($type){
  global $pdo;

  $stmt = $pdo->prepare("SELECT * FROM referrals
                         LEFT JOIN members ON members.mem_id = referrals.ref_referral
                         WHERE ref_type = :type AND ref_referrer = :mem");
  $stmt-> bindValue(':type', $type);
  $stmt-> bindValue(':mem', userId());
  $stmt-> execute();

  $res = array();
  while($result = $stmt->fetch()){
    $res[] = $result;
  }
  return $res;
}

$referrals = returnReferrals($type);

$smarty->assign('referrals', $referrals);

referrals.tpl

{foreach $referrals as $refs}
  
  <!-- Here I need to calculate days difference and have logic like below -->

  {if $days > 2}Inactive{else}Active{/if}

{/foreach}

现在要获取 $days 我需要计算两个日期之间的差异,其中一个日期来自数据库 datetime 字段 $refs.ref_last_click,另一个是当前日期。如果我可以在 PHP 中,我可以很容易地做到这一点,但由于我已经将循环变量分配给要在 foreach 循环中使用的模板,我现在必须在 SMARTY 中进行。我该怎么做?

这是我的 smarty 函数(添加到您的 smarty 插件目录):

/* 
* Smarty plugin 
* ------------------------------------------------------------- 
* Type: function 
* Name: date_diff 
* Purpose: factor difference between two dates in days, weeks, or years
* Input: d1 = "mm/dd/yyyy" or "yyyy/mm/dd" or "yyyy-mm-dd"
*        d2 = "mm/dd/yyyy" or "yyyy/mm/dd" or "yyyy-mm-dd" or $smarty.now
*        assign = name of variable to assign difference to 
*        interval = "days" (default), "weeks", "years" 
* Examples: {date_diff d1="2020-01-20"}
* Examples: {date_diff d1="2020-01-20" d2=2020-02-10 interval="weeks"}
* Examples: {date_diff d1="2020-01-20" d2=2020-02-10 assign="variable_diff"} result: {$variable_diff}
* -------------------------------------------------------------
*/
function smarty_function_date_diff($params, &$smarty)
{
    $d1          = isset($params['d1']) ? $params['d1'] : date('Y-m-d');
    $d2          = isset($params['d2']) ? $params['d2'] : date('Y-m-d');
    $assign_name = isset($params['assign']) ? $params['assign'] : '';

    $date1 = strtotime($d1);
    $date2 = strtotime($d2);

    // use current for empty string
    if (! $date1) {
       $date1 = date('Y-m-d');
    }
    if (! $date2) {
       $date2 = date('Y-m-d');
    }

    $interval = isset($params['interval']) ? $params['interval'] : 'days';

    // diff in days
    $diff = ($date2 - $date1) / 60 / 60 / 24;

    if ($interval === "weeks") {
        $diff /= 7;
    }
    elseif ($interval === "years") {
        $diff /= 365.25;
    }

    $diff = floor($diff);

    if ($assign_name) {
        $smarty->assign($assign_name, $diff);
    }
    else {
        return $diff;
    }

}

然后你的代码:

{foreach $referrals as $refs}

    {date_diff d1=$refs.ref_last_click assign='days'}
    {* 'd2' will appear as default current time *}

    {if $days > 2}Inactive{else}Active{/if}

{/foreach}