Created
November 19, 2013 20:46
-
-
Save imkingdavid/7552249 to your computer and use it in GitHub Desktop.
A simple Twig Filter extension for Symfony2 that converts a JSON Date object into a timestamp that can be used in the PHP date() function.
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 Acme\DemoBundle\Twig; | |
use Twig_Extension; | |
use Twig_Filter_Method; | |
class AcmeExtension extends Twig_Extension | |
{ | |
public function getFilters() | |
{ | |
return array( | |
'parseJsonDate' => new Twig_Filter_Method($this, 'parseJsonDate'), | |
); | |
} | |
/** | |
* Parse a date string from JSON for easier manipulation | |
* Assumed public domain - http://stackoverflow.com/a/16749812/996876 | |
* | |
* @param string $date JSON date string | |
* @param string $format See http://php.net/manual/en/function.date.php | |
* @param string $calculation Perform a calculation to $date using a | |
* string compatible with strtotime() | |
* @return array|bool Timestamp and formatted textual representation | |
*/ | |
public function parseJsonDate($date, $format = 'Y-m-d H:i:s', $calculation = '') | |
{ | |
// Parse the date into timestamp string and timezone string | |
preg_match('/(\d{10})(\d{3})([\+\-]\d{4})/', $date, $matches); | |
// Get the timestamp as the TS tring / 1000 | |
$ts = (int) $matches[1]; | |
if ($calculation) { | |
$ts = strtotime($calculation, $ts); | |
} | |
// Get the timezone name by offset | |
$tz = (int) $matches[3]; | |
$tz = timezone_name_from_abbr("", $tz / 100 * 3600, false); | |
$tz = new \DateTimeZone($tz); | |
// Create a new DateTime, set the timestamp and the timezone | |
$dateTime = new \DateTime(); | |
$dateTime->setTimestamp($ts); | |
$dateTime->setTimezone($tz); | |
// Echo the formatted value | |
return $dateTime->format($format); | |
} | |
public function getName() | |
{ | |
return 'acme_extension'; | |
} | |
} |
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
acme.twig.extension: | |
class: Acme\DemoBundle\Twig\AcmeExtension | |
tags: | |
- { name: twig.extension } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment