2011-02-02 231 views
1

编辑:此功能确实在PHP中工作,它在CakePHP框架内并不适用于我,因为我原本在发布时没有考虑到这一点。将格林尼治标准时间转换为当地时间

此函数采用字符串格式化日期/时间和本地时区(例如'America/New_York')。它应该将时间转换回当地时区。目前,它不会改变。

我传的那样:“2011-01-16 4时57分00秒”,“美国/纽约”和我回去,同时我通过在

function getLocalfromGMT($datetime_gmt, $local_timezone){ 
     $ts_gmt = strtotime($datetime_gmt.' GMT'); 
     $tz = getenv('TZ'); 
     // next two lines seem to do no conversion 
     putenv("TZ=$local_timezone"); 
     $ret = date('Y-m-j H:i:s',$ts_gmt); 
     putenv("TZ=$tz"); 
     return $ret; 
    } 

我见过的引用。到default_timezone_get/set的新方法。我目前没有兴趣使用该方法,因为我希望此代码能够与旧版本的PHP一起工作。

回答

2

显然,在CakePHP中,如果您使用date_default_timezone_set()在你的配置文件,我们是,TZ环境变量设置方法是行不通的。所以,看起来很完美的新版本是:

function __getTimezone(){ 
     if(function_exists('date_default_timezone_get')){ 
      return date_default_timezone_get(); 
     }else{ 
      return getenv('TZ'); 
     } 
    } 

    function __setTimezone($tz){ 
     if(function_exists('date_default_timezone_set')){ 
      date_default_timezone_set($tz); 
     }else{ 
      putenv('TZ='.$tz); 
     } 
    } 

    // pass datetime_utc in a standard format that strtotime() will accept 
    // pass local_timezone as a string like "America/New_York" 
    // Local time is returned in YYYY-MM-DD HH:MM:SS format 
    function getLocalfromUTC($datetime_utc, $local_timezone){ 
     $ts_utc = strtotime($datetime_utc.' GMT'); 
     $tz = $this->__getTimezone(); 
     $this->__setTimezone($local_timezone); 
     $ret = date('Y-m-j H:i:s',$ts_utc); 
     $this->__setTimezone($tz); 
     return $ret; 
    } 
0

这个怎么样

<?php 


     // I am using the convention (assumption) of "07/04/2004 14:45" 
     $processdate = "07/04/2004 14:45"; 


     // gmttolocal is a function 
     // i am passing it 2 parameters: 
     // 1)the date in the above format and 
     // 2)time difference as a number; -5 in our case (GMT to CDT) 
     echo gmttolocal($processdate,-5); 



function gmttolocal($mydate,$mydifference) 
{ 
     // trying to seperate date and time 
     $datetime = explode(" ",$mydate); 

     // trying to seperate different elements in a date 
     $dateexplode = explode("/",$datetime[0]); 

     // trying to seperate different elements in time 
     $timeexplode = explode(":",$datetime[1]); 


// getting the unix datetime stamp 
$unixdatetime = mktime($timeexplode[0]+$mydifference,$timeexplode[1],0,$dateexplode[0],$dateexplode[1],$dateexplode[2]); 

     // return the local date 
     return date("m/d/Y H:i",$unixdatetime)); 
} 


?> 
相关问题