3

Please post any smarty syntax to Get number of days between two dates from my database. i was to able to display all the other fields,but this date field with number of days not working as the way i was expected.Please let me know is there any way to get this solution without any smarty additional plugins.

2 Answers 2

2

Smarty does not include any specific functions for doing date math operations. They have the date_format for timestamps, but otherwise you'd either have to write your own days_diff plugin, find one online, or do the date math in PHP and assign to a new variable in Smarty.

0

Here is my function for this problem:

/* 
* 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;
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.