[英]Compare two dates in smarty
我有兩個各自格式的日期(02-Dec-14 和 17-Dec-14 ),我想在 smarty 中比較這兩個日期。
我如何比較這兩個日期? 請幫忙。
提前致謝
如果您以這種方式將這些日期分配給 Smarty:
$smarty->assign('date2','02-Dec-14');
$smarty->assign('date1','17-Dec-14');
你可以在Smarty中直接使用strtotime
函數,例如:
{if $date1|strtotime < $date2|strtotime}
{$date1} is earlier than {$date2}
{elseif $date1|strtotime == $date2|strtotime}
Both dates are the same
{else}
{$date2} is earlier than {$date1}
{/if}
{if {$date1|date_format:"%y%m%d"} lt {$date2|date_format:"%y%m%d"}}
<?php
$d = '02-Dec-14';
$e = '17-Dec-14';
$t1 = strtotime($d);
$t2 = strtotime($e);
/*
// Test if it works.
if ($t2 > $t1) {
echo 'second is greater';
}
*/
然后您可以將其分配給 Smarty:
$this->assign('date_one', $t1);
$this->assign('date_two', $t2);
在 Smarty 中,您可以比較:
{if $date_one < $date_rwo}
...do something..
{/if}
我嘗試了很多方法,都沒有得到解決方案。 最后我嘗試了這樣的事情:在 PHP 中將 2 個變量傳遞給 smarty:
$insuranceStartDate= date("jS F Y", strtotime($startdate));
$smarty->assign('insuranceStartDate' , $insuranceStartDate);
$insuranceStartDatePlain= date("Y/m/d", strtotime($startdate));
$smarty->assign('insuranceStartDatePlain' , $insuranceStartDatePlain);
在smarty比較如下:
{if $insuranceStartDatePlain|date_format:'%Y/%m/%d' < '2017/09/01'}
less than - 1<sup>st</sup> Septemeber 2017
{else}
greater - {$insuranceStartDate}
{/if}
注意:要比較字符串時的日期,請在 smarty 中使用順序 YYYY/MM/DD
希望它可以幫助將來的人:)
這是我的 smarty 函數(添加到您的 smarty 插件目錄中):
/*
* 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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.