【问题标题】:Smarty Date DifferenceSmarty 日期差异
【发布时间】:2011-05-11 05:59:16
【问题描述】:

请发布任何 smarty 语法以从我的数据库中获取两个日期之间的天数。我本来可以显示所有其他字段,但是这个日期字段的天数没有像我预期的那样工作。请让我知道是否有任何方法可以在没有任何智能附加插件的情况下获得此解决方案。

【问题讨论】:

    标签: smarty


    【解决方案1】:

    Smarty 不包含任何用于进行日期数学运算的特定函数。他们有 date_format 用于时间戳,但否则您要么必须编写自己的 days_diff 插件,在网上找到一个插件,要么在 PHP 中计算日期并在 Smarty 中分配一个新变量。

    【讨论】:

      【解决方案2】:

      这是我解决这个问题的函数:

      /* 
      * Smarty plugin 
      * ------------------------------------------------------------- 
      * Type: function 
      * Name: date_diff 
      * Author: Rafał Pawlukiewicz
      * 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;
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-26
        • 2022-01-19
        • 2012-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多