请发布任何智能语法以获取数据库中两个日期之间的天数。我能够显示所有其他字段,但这个日期字段的天数不像我预期的那样工作。请让我知道有没有办法得到这个解决方案没有任何聪明的额外插件。
答案 0 :(得分:2)
Smarty不包含进行日期数学运算的任何特定函数。他们有date_format
的时间戳,但你要么必须编写自己的days_diff
插件,在网上找到一个(here's one,但首先要进行代码审查),或者做PHP中的日期数学并分配给Smarty中的新变量。
答案 1 :(得分:0)
这是我解决这个问题的函数:
/*
* 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;
}
}