-
-
Save jpgreth/5900168 to your computer and use it in GitHub Desktop.
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 | |
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