Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
4 lines relative date formatter with DateInterval and Symfony2 Translator
<?php
use Symfony\Component\Translation\TranslatorInterface;
function format(\DateTime $date, TranslatorInterface $translator)
{
$diff = date_create()->diff($date);
$seconds = $diff->days * 86400 + $diff->h * 3600 + $diff->i * 60 + $diff->s;
$format = $translator->transChoice('reldate', $seconds);
return $diff->format($format);
}
<?php
$translator = new Translator('en');
$translator->addLoader('array', new ArrayLoader());
$translator->addResource('array', array(
'reldate' => // see http://symfony.com/doc/2.0/book/translation.html#explicit-interval-pluralization
'[0,60[Just now'
.'|[60,120[%i minute ago'
.'|[120,3600[%i minutes ago'
.'|[3600,7200[%h hour ago'
.'|[3600,86400[%h hours ago'
.'|[86400,+Inf[%d days ago',
), 'en');
format(date_create('now - 30 seconds'), $translator); // Just now
format(date_create('now - 2 minutes'), $translator); // 2 minutes ago
format(date_create('now - 1 hour'), $translator); // 1 hour ago
format(date_create('now - 5 days'), $translator); // 5 days ago
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment