Today I was building an RSS feed in Smarty. Pretty straightforward (really, why the hell would you need complex libraries for such a simple tasks??). Anyhow, the database is MySQL and as such, will return MySQL timestamps. RSS requires an rfc2822 timestamp. B0rk.
Luckily, there's Smarty. Or... well... So I thought. Smarty only offers one solution to dates and timestamps; a proxy to strftime. Yeah, nice. And it's bugged too. Whenever I try:
{$variable|date_format:"%Y"}
Assuming the $variable exists, PHP will throw a syntax error.
Interesting fact, when you first encounter this type of error in PHP you'll have no clue what the hell is going on, unless you actually speak Hebrew yourself... The error is "unexpected T_OBJECT_OPERATOR, expecting T_PAAMAYIM_NEKUDOTAYIM". It's telling you it was expecting a double colon...
From
php.net:
[quote]Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew![/quote]
Just another reason why I've started resenting the PHP language... Anyways.
So the date_format Smarty function is broken. No matter, it was quite useless creating a rfc2822 timestamp anyways. And date has a perfect argument, 'r', that will create it for me! If only I had access to date from Smarty (without elaborate hacks)...
Oh, well here you go :)
/**
* Proxy the date function by php.
* Stamp is optional and may be a unix timestamp (number) or a mysql timestamp (Y-d-m H:i:s)
* Usage: {date format=$format stamp=$stamp}
*
* @param array $args
* @param object $objSmarty=false
* @return string
*/
function dateProxy($args, $objSmarty=false) {
if (isset($args['stamp'])) {
$dDate = $args['stamp'];
if ($dDate && (intval($dDate)."") != $dDate) {
// assume mysql timestamp, convert to unixtime
$dDate = mktime(
substr($dDate, 11,2), // hour
substr($dDate, 14,2), // minute
substr($dDate, 17,2), // second
substr($dDate, 5,2)-1, // month
substr($dDate, 8,2), // day
substr($dDate, 0,4) // year
);
}
return date($args['format'], $dDate);
}
return date($args['format']);
}
And to hook it up
$objSmarty->register_function('date', 'dateProxy');
After that you can use date in Smarty like this:
Time: {date format=r stamp=$strTimestamp}
Time: {date format="Y-d-m" stamp=50}
Time: {date format="Y-d-m"}
Time: {date format=$format}
Time: {date format="Y-d-m" stamp="2009-09-23 14:43:52"}
As you can see, you can omit the stamp parameter entirely. You can also supply a MySQL timestamp, which will be converted to a Unix timestamp by the plugin.
Hope it helps ya :)