Smarty Relative Datetime Modifier
Published: 03/24/2009
Programming, Code
In Extending the Smarty Template Engine I outlined the steps needed to create all the varieties of plugins for the Smarty template engine. Continuing with that tutorial, and to provide a little context, here’s a quick Smarty plugin for converting timestamps into relative timestamps.
This is a Smarty module plugin; notice how the name conforms to the naming conventions with the prefix “smarty_modifier_”
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty relative date / time plugin * * Type: modifier<br> * Name: relative_datetime<br> * Date: March 18, 2009 * Purpose: converts a date to a relative time * Input: date to format * Example: {$datetime|relative_datetime} * @author Eric Lamb <eric@ericlamb.net> * @version 1.0 * @param string * @return string */ function smarty_modifier_relative_datetime($timestamp) { if(!$timestamp){ return 'N/A'; } $timestamp = (int)strtotime($timestamp); $difference = time() - $timestamp; $periods = array("sec", "min", "hour", "day", "week","month", "year", "decade"); $lengths = array("60","60","24","7","4.35","12","10"); $total_lengths = count($lengths); if ($difference > 0) { // this was in the past $ending = "ago"; } else { // this was in the future $difference = -$difference; $ending = " from now"; } //return; for($j = 0; $difference > $lengths && $total_lengths > $j; $j++) { $difference /= $lengths; } $difference = round($difference); if($difference != 1) { $periods.= "s"; } $text = "$difference $periods $ending"; return $text; }
Installation
Just copy the contents above and paste into a file called:
modifier.relative_datetime.php
Place the file in your Smarty plugin directory and you’re good to go.
Usage Example:
{$item.timestamp|relative_datetime}