DateTimeTzType.php 2.33 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Types;

5 6
use DateTime;
use DateTimeInterface;
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
use Doctrine\DBAL\Platforms\AbstractPlatform;

/**
 * DateTime type saving additional timezone information.
 *
 * Caution: Databases are not necessarily experts at storing timezone related
 * data of dates. First, of all the supported vendors only PostgreSQL and Oracle
 * support storing Timezone data. But those two don't save the actual timezone
 * attached to a DateTime instance (for example "Europe/Berlin" or "America/Montreal")
 * but the current offset of them related to UTC. That means depending on daylight saving times
 * or not you may get different offsets.
 *
 * This datatype makes only sense to use, if your application works with an offset, not
 * with an actual timezone that uses transitions. Otherwise your DateTime instance
 * attached with a timezone such as Europe/Berlin gets saved into the database with
 * the offset and re-created from persistence with only the offset, not the original timezone
 * attached.
 */
25
class DateTimeTzType extends Type implements PhpDateTimeMappingType
26
{
Benjamin Morel's avatar
Benjamin Morel committed
27 28 29
    /**
     * {@inheritdoc}
     */
30 31
    public function getName()
    {
32
        return Types::DATETIMETZ_MUTABLE;
33
    }
34

Benjamin Morel's avatar
Benjamin Morel committed
35 36 37
    /**
     * {@inheritdoc}
     */
38
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
39 40 41 42
    {
        return $platform->getDateTimeTzTypeDeclarationSQL($fieldDeclaration);
    }

Benjamin Morel's avatar
Benjamin Morel committed
43 44 45
    /**
     * {@inheritdoc}
     */
46 47
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
48
        if ($value === null) {
49 50 51
            return $value;
        }

52
        if ($value instanceof DateTimeInterface) {
53
            return $value->format($platform->getDateTimeTzFormatString());
54
        }
55

56
        throw ConversionException::conversionFailedInvalidType($value, $this->getName(), ['null', 'DateTime']);
57 58
    }

Benjamin Morel's avatar
Benjamin Morel committed
59 60 61
    /**
     * {@inheritdoc}
     */
62 63
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
64
        if ($value === null || $value instanceof DateTimeInterface) {
65
            return $value;
66 67
        }

68
        $val = DateTime::createFromFormat($platform->getDateTimeTzFormatString(), $value);
69
        if ($val === false) {
70
            throw ConversionException::conversionFailedFormat($value, $this->getName(), $platform->getDateTimeTzFormatString());
71
        }
Benjamin Morel's avatar
Benjamin Morel committed
72

73
        return $val;
74
    }
75
}