-
-
Save henrikbjorn/1432795 to your computer and use it in GitHub Desktop.
4 lines relative date formatter with DateInterval and Symfony2 Translator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ah yes, I missread the format function