AppModel-> afterFind (CakePHP'de) saat dilimleri arasında tarihleri ​​dönüştürme

0 Cevap php

Ben farklı saat dilimleri kendi verilerinin tarihleri ​​ve süreleri depolamak iki farklı veri tabanları, veri çekerek bir cakePHP uygulaması var. Bir veritabanının timezone Europe/Berlin, ve diğer en Australia/Sydney olduğunu. Şeyler daha karmaşık hale getirmek için, uygulama ABD'de bir sunucu üzerinde barındırılan ve saatleri yerel saat diliminde son kullanıcıya sunulmalıdır.

Ben erişmek zorunda olduğu veritabanı söylemek için yeterince kolay, ve bu yüzden benim beforeFind, böylece de (date_default_timezone_set() kullanarak) uygun zaman dilimini sorgu doğru bir tarih ile gönderilir timezone.

My problem is then converting the dates in the afterFind to the timezone of the user. I'm passing this timezone through as a named parameter, and to access this in the model I'm using Configure::write() and Configure.read(). This works fine.
The problem is that it seems to be applying my timezone conversion multiple times. For example, if I'm querying the Australia/Sydney database from Australia/Perth the time should be two hours behind, but it's coming out as six hours behind. I tried echoing the times from my function before and after converting them, and each conversion was working correctly, but it was converting the times more than once, and I can't figure out why.

Aşağıdaki gibi şu anda başka bir zaman dilimine dönüştürmek için (benim AppModel olarak) kullanıyorum yöntemleri:

function afterFind($results, $primary){
    // Only bother converting if the local timezone is set.
    if(Configure::read('TIMEZONE'))
        $this->replaceDateRecursive($results);
    return $results;
}

function replaceDateRecursive(&$results){
    $local_timezone = Configure::read('TIMEZONE');

    foreach($results as $key => &$value){
        if(is_array($value)){
            $this->replaceDateRecursive($value);
        }
        else if(strtotime($value) !== false){
            $from_timezone = 'Europe/Berlin';
            if(/* using the Australia/Sydney database */)
                $from_timezone = 'Australia/Sydney';
            $value = $this->convertDate($value, $from_timezone, $local_timezone, 'Y-m-d H:i:s');
        }
    }
}

function convertDate($value, $from_timezone, $to_timezone, $format = 'Y-m-d H:i:s'){
    date_default_timezone_set($from_timezone);
    $value = date('Y-m-d H:i:s e', strtotime($value));
    date_default_timezone_set($to_timezone);
    $value = date($format, strtotime($value));

    return $value;                    
}

Yani herkes dönüşüm birden çok kez oluyor neden olarak herhangi bir fikirleri var mı? Ya da herkes tarihleri ​​dönüştürmek için daha iyi bir yöntem var mı? Açıkçası yanlış bir şey yapıyorum, ben sadece ne olduğu şaşırıp.

0 Cevap