Database engines provide different types for storing date-times. Also, the type naming is often misleading. This documentation page covers the basics and Dbal's solution to the datetime & timezone problem.
Generally, we recognize three types of date time types:
The following table presents a matrix of available data-time types and their behavior:
Local DateTime | UTC DateTime | Zoned DateTime | |
---|---|---|---|
no timezone handling | timezone conversion | timezone stored | |
MySQL | datetime |
timestamp |
– |
Postgres | timestamp |
timestamptz |
– |
SQL Server | datetime , datetime2 |
– | datetimeoffset |
Dbal offers connection time zone configuration option
(connectionTz
) which defines the timezone for database connection
communication; by default it equals to PHP's current default timezone. This
option is configured by timezone name, e.g. Europe/Prague
string.
By default, MySQL server doesn't support named timezones, see the setup chapter how to configure them.
Still, there is a possibility to pass only a timezone offset, e.g.
+03:00
, but this is not ideal. Use magic auto-offset
value that will be dynamically converted to the current PHP's timezone
offset.
This will make Dbal fully functional, although some SQL queries and
expressions may not return correctly calculated results, e.g. functions that
calculate two-date operations directly in the database –
TIMEDIFF
, ADDDATE
, etc.
Dbal comes with two query modifiers:
%dt
(as datetime): converts DateTime object to
connection timezone;%dts
(as datetime simple): pass DateTime object as it
is, without any timezone conversion and identification;Local DateTime | UTC DateTime | Zoned DateTime | |
---|---|---|---|
no timezone handling | timezone conversion | timezone stored | |
MySQL | %dts |
%dt |
– |
Postgres | %dts |
%dt |
– |
SQL Server | %dts |
– | %dt |
Database drivers also correctly read the stored values and convert them into
DateTimeImmutable
instances:
timestamp
column in
connection's timezone and converts it to PHP's default timezone;timestamptz
(timezoned timestamp)
and converts it to PHP's default timezone;datetimeoffset
(timezoned
timestamp) and does not do any timezone conversion;