Nasıl kolayca PHP ile UTC tarihleri ​​dönüştürebilirsiniz?

6 Cevap php

Ben UTC datetime alanlarında MySQL veritabanı tarihleri ​​depolamak. (Zaman damgası olmadan), bugüne kadar tüm aramalar () UTC tarihi döndürür böylece PHP kullanıyorum, ve ben ('UTC') date_timezone_set aradım.

Ben o zaman, belirli bir web sitesi, zaman dilimini seçebilirsiniz o var. Şimdi sitenin diliminde görüntülemek için tarih istiyor. Ben '2009-04-01 15:36:13 olarak depolanan bir tarih var ise, 'bu PDT timezone bir kullanıcı için göstermesi gerekir (-7 saat) olarak '2009-04-01 08:36:13' .

PHP ile bunu yapmak için en kolay (az kod) yöntemi nedir? Şimdiye kadar düşündüm hepsi bu

date('Y-m-d H:i:s', strtotime($Site->getUTCOffset() . ' hours', strtotime(date($utcDate))));

Kısa bir yolu var mı?

6 Cevap

Burada bizim sunucuları ile yaptık. Biz UTC kullanmak için her şeyi ayarlamak, ve biz anında UTC dönüştürerek kullanıcının saat diliminde görüntüler. Bu yazının altındaki kodu bu işe almak için nasıl bir örnek; Eğer bu kurulum (yani ışığından, vb) ile tüm durumlarda çalıştığını teyit etmelidir.

Configuring CentOS

  1. Düzenleme /etc/sysconfig/clock ve ZONE UTC ayarlandığında
  2. ln -sf /usr/share/zoneinfo/UTC /etc/localtime

Configuring MySQL

  1. MySQL içine İthalat dilimleri gerekirse:

    mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql

  2. Düzenleme my.cnf ve [mysqld] bölümüne içinde aşağıdakileri ekleyin:

    default-time-zone = 'UTC'

PHP Code

<?php
/*
Example usage:
  $unixtime = TimeUtil::dateTimeToTimestamp('2009-04-01 15:36:13');
  echo TimeUtil::UTCToPST("M d, Y - H:i:s", $unixtime);
*/

// You should move this to your regular init method
date_default_timezone_set('UTC'); // make this match the server timezone

class TimeUtil {
    public static function timestampToDateTime($timestamp) {
        return gmdate('Y-m-d H:i:s', $timestamp);
    }

    public static function dateTimeToTimestamp($dateTime) {
        // dateTimeToTimestamp expects MySQL format
        // If it gets a fully numeric value, we'll assume it's a timestamp
        // You can comment out this if block if you don't want this behavior
        if(is_numeric($dateTime)) {
            // You should probably log an error here
            return $dateTime;
        }
        $date = new DateTime($dateTime); 
        $ret = $date->format('U');
        return ($ret < 0 ? 0 : $ret);
    }

    public static function UTCToPST($format, $time) {
        $dst = intval(date("I", $time));
        $tzOffset = intval(date('Z', time()));
        return date($format, $time + $tzOffset - 28800 + $dst * 3600);
    }

}

Neden kullanmayın DateTime/TimeZone işlevselliği yerleşik?

<?php

$mysqlDate = '2009-04-01 15:36:13';

$dateTime = new DateTime ($mysqlDate);
$dateTime->setTimezone(new DateTimeZone('America/Los_Angeles'));

?>

DateTime Class: http://us3.php.net/manual/en/class.datetime.php DateTimeZone Class: http://us3.php.net/manual/en/class.datetimezone.php

PHP'nin desteklediği Timezones: http://php.net/manual/en/timezones.php

Ne yapıyoruz şeyler yapmanın doğru yoldur. Ben sadece UTC çalışan ve sadece ekran için son dakikada dönüştürme ile yapışmasını tavsiye ederim.

Burada PHP ile birlikte DateTime sınıfını kullanarak bir zaman dilimi dönüşüm için bir araya hızlı bir fonksiyon. Size sahip biraz daha kod ama şeyleri yapısı için daha iyi bir yol daha kolay ve düşünüyorum ...

function convert_time_zone($date_time, $from_tz, $to_tz)
    {
    $time_object = new DateTime($date_time, new DateTimeZone($from_tz));
    $time_object->setTimezone(new DateTimeZone($to_tz));
    return $time_object->format('Y-m-d H:i:s');
    }

http://richardwillia.ms/blog/2011/04/time-zone-conversion-using-datetime-class/

Umut olur.

Bu konu ile ilgili çok zaman geçiren, do not attempt to implement time zone translation yourself. Bu zorluklarla dolu bir kraliyet PIA,, ve o sağ uluslararası bunu almak çok zor.

O dedi, en iyi seçenek timestamp s MySQL sizin datetime s dönüştürmek ve sadece kez dönüştürmek için veritabanı kullanmak için:

 mysql> set time_zone='America/New_York';

timestamp s MySQL küçüktür ve destek zaman dilimi çeviri. datetime yok.

Eğer sayfada site bilgilerini görüntülemek için önce, sadece yukarıdaki komutu çağırmak ve hiç bir PHP kodu değişiklikleri olmadan doğru gösterecektir.

Uyarılar:

  1. Eğer NOW() ya da herhangi bir yerel zamanı işlevlerini kullanırsanız, UTC_TIMESTAMP() bunları güncelleştirmek gerekir
  2. timestamp s ilginç bir güncelleme var ve kapatmak isteyebilirsiniz özelliklerini eklemek.

timestamp özelliklerini kapatmak için:

ALTER TABLE mytable CHANGE COLUMN Created Created timestamp NULL DEFAULT 0;

DEFAULT 0 diğer sütunlar güncelleştirmek zaman sütun güncellenmektedir devre dışı bırakır.

<?php

  function getNoteDateTimeZone($date = null, $from_dtz = 'US/Central', $to_dtz = null) {
        //$from_zt = 'US/Central'; // Time Zone = -06:00
        if (is_null($date) == FALSE && is_null($from_dtz) == FALSE && is_null($to_dtz) == FALSE) {
            // set TimeZone from
            $time_object = new DateTime($date, new DateTimeZone($from_dtz));
            $time_now_object = new DateTime("now", new DateTimeZone($from_dtz));
            // Change TimeZone
            $time_object->setTimezone(new DateTimeZone(trim($to_dtz)));
            $time_now_object->setTimezone(new DateTimeZone(trim($to_dtz)));
            // Is day = day in $time_now_object, $time_object..?
            if ($time_now_object->format('d') == $time_object->format('d')) {
                return $time_object->format('H:i:s');
            } else {
                return $time_object->format('Y-m-d H:i:s');
            }
        } else {
            return '';
        }
    }
?>

Örnek kullanın:

<?php 
 $date = '2008-06-02 20:32:46';
 $dtz = 'America/Argentina/Buenos_Aires';
 echo getNoteDateTimeZone($date, 'US/Central', $dtz); // Out = 2008-06-02 23:32:46
?>

Bu benim için çalıştı ve oldukça temiz

function convert_to_user_date($date, $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC', $format = 'n/j/Y g:i A')
{
    $dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
    $dateTime->setTimezone(new DateTimeZone($userTimeZone));
    return $dateTime->format($format);
}

function convert_to_server_date($date, $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC', $format = 'n/j/Y g:i A')
{
    $dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
    $dateTime->setTimezone(new DateTimeZone($serverTimeZone));
    return $dateTime->format($format);
}