4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Form\Extension\Core\DataTransformer
;
14 use Symfony\Component\Form\Exception\TransformationFailedException
;
17 * Transforms between a timestamp and a DateTime object
19 * @author Bernhard Schussek <bschussek@gmail.com>
20 * @author Florian Eckerstorfer <florian@eckerstorfer.org>
22 class DateTimeToTimestampTransformer
extends BaseDateTimeTransformer
25 * Transforms a DateTime object into a timestamp in the configured timezone.
27 * @param \DateTime $value A \DateTime object
29 * @return integer A timestamp
31 * @throws TransformationFailedException If the given value is not an instance
32 * of \DateTime or if the output
33 * timezone is not supported.
35 public function transform($value)
37 if (null === $value) {
41 if (!$value instanceof \DateTime
) {
42 throw new TransformationFailedException('Expected a \DateTime.');
45 $value = clone $value;
47 $value->setTimezone(new \
DateTimeZone($this->outputTimezone
));
48 } catch (\Exception
$e) {
49 throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e);
52 return (int) $value->format('U');
56 * Transforms a timestamp in the configured timezone into a DateTime object
58 * @param string $value A timestamp
60 * @return \DateTime A \DateTime object
62 * @throws TransformationFailedException If the given value is not a timestamp
63 * or if the given timestamp is invalid.
65 public function reverseTransform($value)
67 if (null === $value) {
71 if (!is_numeric($value)) {
72 throw new TransformationFailedException('Expected a numeric.');
76 $dateTime = new \
DateTime();
77 $dateTime->setTimezone(new \
DateTimeZone($this->outputTimezone
));
78 $dateTime->setTimestamp($value);
80 if ($this->inputTimezone
!== $this->outputTimezone
) {
81 $dateTime->setTimezone(new \
DateTimeZone($this->inputTimezone
));
83 } catch (\Exception
$e) {
84 throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e);