For use in controllers or services, autowire or inject the Knp\Bundle\TimeBundle\DateTimeFormatter service. It provides methods to format differences, durations, and ages.
use Knpundle ime-bundle\
DateTimeFormatter;
public function yourAction(DateTimeFormatter $dateTimeFormatter)
{
$someDate = new \DateTimeImmutable('-2 years');
$toDate = new \DateTimeImmutable('now');
// Formats difference between two dates (defaults to 'now' if second param is omitted)
$agoTime = $dateTimeFormatter->formatDiff($someDate, $toDate);
// Formats seconds into a duration string
$readTime = $dateTimeFormatter->formatDuration(64);
// Formats age (defaults to 'now' if second param is omitted)
$ageTime = $dateTimeFormatter->formatAge($someDate, $toDate);
return $this->json([
'published_at' => $agoTime, // 2 years ago
'read_time' => $readTime, // 1 minute
'age' => $ageTime, // 2 years old
]);
}