Skip to content

Instantly share code, notes, and snippets.

@henrikbjorn
Forked from arnaud-lb/RelDate.php
Created December 5, 2011 08:01
Show Gist options
  • Save henrikbjorn/1432795 to your computer and use it in GitHub Desktop.
Save henrikbjorn/1432795 to your computer and use it in GitHub Desktop.
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,172800[%h day ago'
.'|[86400,31556926[%d days ago',
.'|[31556926,63113852[%y year ago',
.'|[63113852,+Inf[%d years 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
@stof
Copy link

stof commented Dec 5, 2011

ah yes, I missread the format function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment