Skip to content

Instantly share code, notes, and snippets.

@clauswitt
Created November 15, 2011 13:48
Show Gist options
  • Save clauswitt/1367106 to your computer and use it in GitHub Desktop.
Save clauswitt/1367106 to your computer and use it in GitHub Desktop.
A simple "how long ago" viewhelper for Flow3
<?php
namespace ClausWitt\ViewHelpers;
/**
* A view helper for getting a specific date as "how along ago"
*
*
*/
class AgoViewHelper extends \TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper {
/**
* @var string
*/
protected $tagName = 'span';
/**
* @param \DateInterval $dateDifference
*/
private function renderDateDifference($dateDifference) {
$str = 'from now';
if($dateDifference->format('R')=='-') {
$str = 'ago';
}
if($dateDifference->y > 0) {
return $dateDifference->y . ' years ' . $str;
}
if($dateDifference->m > 0) {
return $dateDifference->m . ' months ' . $str;
}
if($dateDifference->d > 0) {
if($dateDifference->d>7) {
$weeks = $dateDifference->d / 7;
$weeks = \round($weeks);
return $weeks . ' weeks ' . $str;
}
return $dateDifference->d . ' days ' . $str;
}
if($dateDifference->h > 0) {
return $dateDifference->h . ' hours ' . $str;
}
if($dateDifference->i > 0) {
return $dateDifference->i . ' minutes ' . $str;
}
if($dateDifference->s > 0) {
return 'just now';
}
}
/**
* Render the supplied DateTime as a string indicating how long ago (or from now) the given time is. It is rendered
* as the largest possible value.
*
* Years if they are set.
* then months if they are set.
* then weeks or days if days are set
* then hours if they are set
* then minutes if they are set
*
*
* @param mixed $date either a \DateTime object or a string that is accepted by \DateTime constructor
*
* @return string Formatted date
* @api
*/
public function render($date = NULL) {
if($date === NULL) {
$date = $this->renderChildren();
if($date === NULL) {
return '';
}
}
if(!$date instanceof \DateTime) {
try {
$date = new \DateTime($date);
} catch(\Exception $exception) {
throw new \TYPO3\Fluid\Core\ViewHelper\Exception('"' . $date . '" could not be parsed by \DateTime constructor.', 1241722579);
}
}
$diff = $date->diff(new \DateTime());
return $this->renderDateDifference($diff);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment