Calculating the difference between dates with Smarty Tags

This page describes how to perform calculations based on date fields. This action can be used in Merge Templates.

Calculate the number of days between two dates

In the case where you have two date fields and need to determine the number of days between those two dates, you can use the following formula. Before jumping into the formula, let's assume:

  • Date 1 = $projectteam_0001

  • Date 2 = $projectteam_0002

There is not a way to easily calculate between two formatted dates using Smarty Tags so you will need to convert each date to a flat number first. You can use the timestamp function "@strtotime" to get the number of seconds that have passed since January 1, 1970 (that date was determined by php/Smarty).

 

Therefore, you can assign a new variable to get those two numbers:

  • {assign var=num1 value=$projectteam_0001|@strtotime}

  • {assign var=num2 value=$projectteam_0002|@strtotime}

Now that the numbers are formatted to be flat numbers, you can include a new variable to find the difference between them:

  • {assign var=diff value=$num1-$num2}

You're close, but now your {$diff} result would be the number of seconds between your two dates. You need to divide your number by the number of seconds in a day, or 86,400 (60x60x24).

  • {assign var=final value=$diff/86400}

Therefore, the final formula is:

{assign var=num1 value=$projectteam_0001|@strtotime}
{assign var=num2 value=$projectteam_0002|@strtotime}
{assign var=diff value=$num1-$num2}
{assign var=final value=$diff/86400}
{$final}

 

If you don't want all the extra space in your output, remove the line breaks:

{assign var=num1 value=$projectteam_0001|@strtotime}{assign var=num2 value=$projectteam_0002|@strtotime}{assign var=diff value=$num1-$num2}{assign var=final value=$diff/86400}{$final}

 

Determine the new date based on an existing date and a number of days

Let's say you have a date field called "Original Date" and a number field called "Impact Days". You would like to calculate a new date based on your two existing fields. For this, let's assume:

  • Date = $projectteam_0001

  • Number = $projectteam_0002

Similar to the example above, you will first need to get your original date field into a flat number format. So you can use:

  • {assign var=num1 value=$projectteam_0001|@strtotime}

Remember, this will give you the number of seconds passed related to your date field from January 1, 1970. So now you need to convert your days field to be represented in seconds as well. Multiple your field by 86,400:

  • {assign var=num2 value=$projectteam_0002*86400}

Both of your data elements are represented in a flat number, seconds. You can add those together:

  • {assign var=num3 value=$num1+$num2}

Finally, your final result should be be re-formatted back into a date. So you will need to apply the "date_format" tag:

  • {$num3|date_format:”%Y-%m-%d”}