cakephp icon indicating copy to clipboard operation
cakephp copied to clipboard

ORM does not automatically convert timezones to the application timezone upon saving

Open samuelszabo opened this issue 8 years ago • 12 comments

This is a (multiple allowed):

  • [x] bug

  • [ ] enhancement

  • [ ] feature-discussion (RFC)

  • CakePHP Version: 3.5.12

  • Platform and Target: built-in server, PHP 7.1.5, MySQL 5.6.34

What you did

I would like to save 2 Time objects in different timezones:

$entity = $this->newEntity([
    'date1' => new Time('2018-02-12 11:05:00', '+05:00'),
    'date2' => new Time('2018-02-12 11:05:00', 'UTC')
]);
$this->save($entity);

What happened

Saved dates are both same 2018-02-12 11:05:00 (in DB)

What you expected to happen

I expect Time object timezone should be changed to UTC before saving, so times in DB will be in UTC date1 = '2018-02-12 06:05:00' date2 = '2018-02-12 11:05:00'

I have UTC both in app.php (Datasources.default.timezone) and bootstrap.php (date_default_timezone_set('UTC')), on fresh app install.

setTimezone() will do what am expecting, but I think this is not expected behavior.

$entity = $this->newEntity([
    'date1' => (new Time('2018-02-12 11:05:00', '+05:00'))->setTimezone('UTC'),
    'date2' => new Time('2018-02-12 11:05:00', 'UTC')
]);
$this->save($entity);

saves correct 2018-02-12 06:05:00 for date1.

samuelszabo avatar Feb 12 '18 15:02 samuelszabo

Seems like duplicate of #6571

ADmad avatar Feb 12 '18 15:02 ADmad

The ORM internals don't currently automatically translate timezones for you. You'd need to do this yourself. As an alternative solution you could replace the Datetime type mappings with an implementation that has different toDatabase or marshal logic. See the following for the current code. https://github.com/cakephp/cakephp/blob/a6c47f15e2dfbb062fcc547d6eecd0a944dc8b17/src/Database/Type/DateTimeType.php#L110-L120

This is likely related to #10877 and #11517. These issues aim to add a hidden timezone input enabling the marshaller to convert request data in the user's timezone to the application's internal default timezone.

markstory avatar Feb 12 '18 20:02 markstory

@ADmad Thanks, I did not found it before. This issue is probably part of #6571, but it needs simplier solution (as I hope).

@markstory Thanks, I understand I can fix it my way. But I still consider this (ignoring Timezone) as a bug.

#11517 will not solve this (I may use Time object from other sources than visitor input). I am importing data from third-party source, with dates in different timezone, so I end up with

$timeToSave = new Time('2018-02-12 11:05:00', '+05:00');

I expect after saving $timeToSave to DB I will retrieve same Time object

$entity->date->toUnixString() === (new Time('2018-02-12 11:05:00', '+05:00'))->toUnixString()

Application know database timezone and saving object timezone. So I expect Time will be saved correctly.

$entity = $this->newEntity([
    'date' => (new Time('2018-02-12 11:05:00', '+05:00'))
]);
$this->save($entity);

$entityFromDb = $this->get(1);

I expect $entity->date to be same as $entityFromDb->date.

I understand ORM should not change strings before creating queries, but Time is not string. It is DateTime object with defined timezone, so we know exact value for any timezone. And if database is in different TZ, it should be saved correctly.

When retrieving date from DB, Application expect it is in specific TZ (according to config). And Vice Versa when saving data, I think Application should also save data in correct TZ.

Do you agree?

I think this should be solution: Value should be setted to correct timezone, only if we know inserted TZ (eg. $value is not string nor timestamp) and TZ of DB/driver is setted.

DateTimeType.php https://github.com/cakephp/cakephp/blob/master/src/Database/Type/DateTimeType.php#L110

public function toDatabase($value, Driver $driver)
    {

    ...

        if ($value instanceof \DateTime) {
            if (!empty($driver->getTimezone())) {
                $tz = $driver->getTimezone();    //todo $driver->_config['timezone']
                $value->setTimezone(new \DateTimeZone($tz));
            }
        }

        $format = (array)$this->_format;

        return $value->format(array_shift($format));
    }

Thank for your time.

samuelszabo avatar Feb 13 '18 20:02 samuelszabo

    $entity=$this->Posts->newEntity([
      'date'=>(new Time('2018-02-12 11:05:00', '+05:00'))->setTimezone(date_default_timezone_get())
    ]);
    $this->Posts->save($entity);
    $new = $this->Posts->get($entity->id);
    debug($entity);debug($new);

//result
//$new ===$entity

currently you should use like above

saeideng avatar Feb 13 '18 21:02 saeideng

Perhaps we can modify DateTimeType like this in 3.6:

diff --git a/src/Database/Type/DateTimeType.php b/src/Database/Type/DateTimeType.php
index 6efb905..82400cc 100644
--- a/src/Database/Type/DateTimeType.php
+++ b/src/Database/Type/DateTimeType.php
@@ -18,6 +18,7 @@ use Cake\Database\Driver;
 use Cake\Database\Type;
 use Cake\Database\TypeInterface;
 use DateTimeInterface;
+use DateTimeZone;
 use Exception;
 use PDO;
 use RuntimeException;
@@ -90,6 +91,8 @@ class DateTimeType extends Type implements TypeInterface
      */
     protected $_className;

+    protected $_timezone;
+
     /**
      * {@inheritDoc}
      */
@@ -119,6 +122,9 @@ class DateTimeType extends Type implements TypeInterface

         $format = (array)$this->_format;

+        $timezone = $this->_timezone ?: date_default_timezone_get();
+        $value->setTimezone(new DateTimeZone($timezone));
+
         return $value->format(array_shift($format));
     }

@@ -267,6 +273,13 @@ class DateTimeType extends Type implements TypeInterface
         return $this;
     }

+    public function setTimezone($timezone)
+    {
+        $this->_timezone = $timezone;
+
+        return $this;
+    }
+
     /**
      * Change the preferred class name to the FrozenTime implementation.
      *

ADmad avatar Feb 13 '18 21:02 ADmad

#11517 will not solve this (I may use Time object from other sources than visitor input). I am importing data from third-party source, with dates in different timezone, so I end up with ...

I think #11517 is an important first step to making timezones work more consistently. Your use case is an additional scenario to me.

When retrieving date from DB, Application expect it is in specific TZ (according to config). And Vice Versa when saving data, I think Application should also save data in correct TZ.

Do you agree?

Yes, but I'm not sure that having the ORM automatically handle all those conversions is going to be a transparent and understandable operation to users. This would need to be an opt-in feature as it will impact ORM performance and replacing the current behavior will likely break existing applications.

I think this should be solution: Value should be setted to correct timezone, only if we know inserted TZ (eg. $value is not string nor timestamp) and TZ of DB/driver is setted.

When it comes time to save entities, the marshalling process should have already converted strings and timestamps into datetime objects, so there would be no way to backtrace those values to string/integers making the proposed conditions hard to implement and enforce.

markstory avatar Feb 14 '18 02:02 markstory

@markstory Thanks.

samuelszabo avatar Feb 14 '18 06:02 samuelszabo

@ADmad Thanks, but date_default_timezone_get() may be (even though it is not recommended) different from DB timezone (as in #6571). I prefer exact DB TZ config (which already exists in MySql and Postgres drivers.

samuelszabo avatar Feb 14 '18 06:02 samuelszabo

@samuelszabo That is why I have provided method setTimezone(), trying to read it directly from Driver config would be too much coupling plus all drivers might not have the timezone info.

ADmad avatar Feb 14 '18 08:02 ADmad

@ADmad Thanks. And where/how will be DateTimeType.setTimezone() called?

samuelszabo avatar Feb 14 '18 08:02 samuelszabo

In bootstrap here.

ADmad avatar Feb 14 '18 08:02 ADmad

At least three of the supported databases (oracle, sqlserver, postgresql) have support for some kind of "Timestamp with timezone" Datatype. This way you can make sure that if you store a date in pacific standard time, you'll receive the same data in pacific standard time again. i guess thats an even cleaner solution than automatically transforming the timezones back and forth. So it may be an even better approach to

  • implement Timestamp with timezone support for those three and
  • implement timezone normalization/mapping as a fallback for MySql and Sqlite drivers.

BGehrels avatar Feb 25 '18 15:02 BGehrels