用户评论:

[#1]

Jesse dot Chisholm at gmail dot com [2015-04-19 00:10:38]

I found a need to change the timezone based on a DB record, so it would display properly for each record.  So I wrapped some of the other posts into this small class:

private$stack= array();

public function__construct(){}

public functionpush($newTZ)

{array_push($this->stack,date_default_timezone_get());

if (isset($newTZ) && (""!=$newTZ))

{date_default_timezone_set($newTZ);

}

}

public functionpop()

{

if (count($this->stack) >0)

{date_default_timezone_set(array_pop($this->stack));

}

}

}// the global TZ stack for the rest of the code  to use.$tzStack= newTZStack();// In case I need to know the TZ at the web server. :)$script_tz=date_default_timezone_get();?>

Then in my per-record code:

{$tzStack->push($item['TZ']);$TZ=date("T",time());// code that displays this record, using $TZ.$tzStack->pop();

}?>

[#2]

Anteaus [2015-01-02 00:04:49]

This creates a huge problem for downloadable programs, which obviously cannot be hardcoded as this suggests, since the coder has no idea where they will be run.

Seems to me that if the server's timezone cannot be relied on, then THAT is the the problem which needs fixed. Not, cause the coder's syntactically-correct work to generate bogus error messages.

[#3]

Taylor [2014-05-30 21:47:57]

I was having major issues with the date.timezone setting after I updated from 5.3.3 to 5.4.29. I still need to update further, and perhaps it's a bug in this version that will be fixed when I update..

But to fix the issue of php not being about to find my time zone, I added a .htaccess file to the root of my web directory. All I have in it is this one line (without quotes)

"php_value date.timezone America/Denver"

And now the timezone is set in any directory I browse in. Very strange, and I still haven't figured out why It wont work from the php.ini file. But here's how to overcome the frustration.

[#4]

chris at clwill dot com [2013-12-10 23:54:25]

I'm sure I'm not the only one who is distressed by the recent default behavior change to E_NOTICE when the timezone isn't explicitly set in the program or in .ini.  I insure that the clock on the server IS correct, and I don't want to have to set it in two places (the system AND PHP).  So I want to read it from the system.  But PHP won't accept that answer, and insists on a call to this function.  So, here's my answer:

// to the file with the timezone infoif (is_link("/etc/localtime")) {// If it is, that file's name is actually the "Olsen" format timezone$filename=readlink("/etc/localtime");$pos=strpos($filename,"zoneinfo");

if ($pos) {// When it is, it's in the "/usr/share/zoneinfo/" folder$timezone=substr($filename,$pos+strlen("zoneinfo/"));

} else {// If not, bail$timezone=$default;

}

}

else {// On other systems, like Ubuntu, there's file with the Olsen time

// right inside it.$timezone=file_get_contents("/etc/timezone");

if (!strlen($timezone)) {$timezone=$default;

}

}date_default_timezone_set($timezone);

}?>

Use it by calling it with a fallback default answer.

Yes, I know it doesn't work on Windows.  Neither do I :)  Perhaps someone wants to add that functionality.

Hope this helps someone.

[#5]

Christopher Kramer [2013-03-09 21:39:40]

Regarding my post 3 years before:

The performance impact seems to be caused by the fact that a log message is written if you do not set a timezone. And writing a log message to disk can take significantly longer than actually calculating date() or getdate() - esp. on systems with slow IO like the Windows machine I used 3 years ago.

PHP 4 did not produce any log messages, and therefore was as fast as PHP5 with a timezone set.

So if you run date() or getdate() a lot of times, this will cause a lot of log messages to be written to disk (if you did not disable them in your php.ini settings), which will take its time.

So either use this function or set the ini-setting "date.timezone" to make things faster.

(And have a look into your logfiles! Solving all those warnings will not only save you disk space but will also speed up your web application.)

[#6]

Pierre Gourlaouen [2012-07-06 08:45:52]

A simple method for conversation between two time zone.

$date= newDateTime("2012-07-05 16:43:21", newDateTimeZone('Europe/Paris'));date_default_timezone_set('America/New_York');

echodate("Y-m-d h:iA",$date->format('U'));// 2012-07-05 10:43AM?>

[#7]

daneiracleous at gmail dot com [2012-01-28 08:11:24]

If you want to set the default timezone to the user's local timezone, you have to combine PHP and JavaScript. Here's how to do it:

session_start();

if(!isset($_SESSION['timezone']))

{

if(!isset($_REQUEST['offset']))

{?>

var d = new Date()

var offset= -d.getTimezoneOffset()/60;

location.href = "<?phpecho $_SERVER['PHP_SELF'];?>?offset="+offset;

else

{$zonelist= array('Kwajalein'=> -12.00,'Pacific/Midway'=> -11.00,'Pacific/Honolulu'=> -10.00,'America/Anchorage'=> -9.00,'America/Los_Angeles'=> -8.00,'America/Denver'=> -7.00,'America/Tegucigalpa'=> -6.00,'America/New_York'=> -5.00,'America/Caracas'=> -4.30,'America/Halifax'=> -4.00,'America/St_Johns'=> -3.30,'America/Argentina/Buenos_Aires'=> -3.00,'America/Sao_Paulo'=> -3.00,'Atlantic/South_Georgia'=> -2.00,'Atlantic/Azores'=> -1.00,'Europe/Dublin'=>0,'Europe/Belgrade'=>1.00,'Europe/Minsk'=>2.00,'Asia/Kuwait'=>3.00,'Asia/Tehran'=>3.30,'Asia/Muscat'=>4.00,'Asia/Yekaterinburg'=>5.00,'Asia/Kolkata'=>5.30,'Asia/Katmandu'=>5.45,'Asia/Dhaka'=>6.00,'Asia/Rangoon'=>6.30,'Asia/Krasnoyarsk'=>7.00,'Asia/Brunei'=>8.00,'Asia/Seoul'=>9.00,'Australia/Darwin'=>9.30,'Australia/Canberra'=>10.00,'Asia/Magadan'=>11.00,'Pacific/Fiji'=>12.00,'Pacific/Tongatapu'=>13.00);$index=array_keys($zonelist,$_REQUEST['offset']);$_SESSION['timezone'] =$index[0];

}

}date_default_timezone_set($_SESSION['timezone']);//rest of your code goes here?>

[#8]

power2all at gmail dot com [2011-02-01 08:30:24]

After poundering and knocking my head on the table, I finally got a proper fix for Windows and PHP timezone handling.

Since Windows applies the DST to ActiveTimeBias in the registry, you only need this to apply.

The only problem is, that it cant use the timezone_set command.

You can request a response back in any date-format you wish, or use the default one given in the function itself.

{$shell= newCOM("WScript.Shell") or die("Requires Windows Scripting Host");$time_bias= -($shell->RegRead("HKEY_LOCAL_MACHINE\\SYSTEM\\

CurrentControlSet\\Control\\TimeZoneInformation\\

ActiveTimeBias")) /60;$timestamp_bias=60*60*$time_bias;

echo$time_bias."
";

returngmdate($timeGiven,strtotime($timestamp_bias." seconds"));

}?>

[#9]

Anonymous [2010-11-20 13:58:56]

People complaining that there's no way to set the offset - you are wrong. You can easily set the offset from GMT (see "Other" in available zones). And since all zones are offset from GMT it's just easy math with + or - to get that. So if you i.e. want the offset not from GMT but your timezone, then compute offset of your zone from GMT (say if you in Berlin its +1 now (mind summer time!)) and then offset for your target zone (i.e NYC is -5) then sum abs! of these values and set the sign of bigger (abs) value -> total offset from your european zone to NYC is then abs(-5)+abs(1) = 6 and set "-" as NYC zone absolute value is bigger. So whatever time is in Berlin, in NYC it's 6hrs earlier. But it's better to do two step calculation and calculate always from GMT

[#10]

steve at pozzie dot net [2010-10-11 01:35:20]

Most of the scripts here depend on PHP identifying the correct zone when one is not set, but that does not always happen.

For example PHP 5.3.3 gives a 'UTC' result for a detected '8.0/no DST'. Not much help.

So for those of us who for very good reasons really cannot set time zones in scripts of in .ini files, here is a function

for use in a Windows environment that sets the default time zone to the OS time zone and returns the detected and set texts.

<?phpfunctiondate_system_timezone_set (){$shell= newCOM("WScript.Shell") or die("Requires Windows Scripting Host");$time_bias= -($shell->RegRead("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control

\\TimeZoneInformation\\Bias"))/60;$ab= -($shell->RegRead("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control

\\TimeZoneInformation\\ActiveTimeBias"))/60;$sc=$shell->RegRead("HKEY_USERS\\.DEFAULT\\Control Panel\\International\\sCountry");

foreach(timezone_abbreviations_list() as$tza) foreach($tzaas$entry){$country=strtok($entry['timezone_id'],'/');$locale=strtok('|');

if($country==$sc&&$ab==($entry['offset']/60/60) && ($ds=$time_bias!=$ab)==$entry['dst']){date_default_timezone_set($timezone_identifier=$country."/".$locale);

returnsprintf('%.1f',$ab)."/".($ds?'':'no ').'DST'." ".$timezone_identifier;

}

}

returnfalse;

}?>

[#11]

Tom S [2010-09-11 06:22:54]

This is a good script if you know or control your system so that you know that the local TZ in your OS is correct. Unfortunately, this script still creates an warning message under BSD UNIX.

To fix this, just add an "@" in front of "localtime" as:

$arr = @localtime($iTime);

[#12]

Frederick Hathaway [2010-03-04 08:54:40]

It's really a hassle that there is no way to set the timezone offset. I attempted to use the code that searched for the correct timezone name by offset from below. I found it didn't work reliably since various cities may have different rules about time DST etc. My solution is to actually search the array and do a test to insure the offset is what I expect it to be. It seems very kludgey (if thats a word) but it works.

{$testTimestamp=time();date_default_timezone_set('UTC');$testLocaltime=localtime($testTimestamp,true);$testHour=$testLocaltime['tm_hour'];$abbrarray=timezone_abbreviations_list();

foreach ($abbrarrayas$abbr)

{//echo $abbr."
";foreach ($abbras$city)

{date_default_timezone_set($city['timezone_id']);$testLocaltime=localtime($testTimestamp,true);$hour=$testLocaltime['tm_hour'];$testOffset=$hour-$testHour;

if($testOffset==$offset)

{

returntrue;

}

}

}

returnfalse;

}?>

[#13]

Christopher Kramer [2010-01-09 07:52:21]

I experienced that using this function highly increases performance of functions like getdate() or date() using PHP 5.2.6 on Windows.

I experienced similar results on Linux servers with PHP 5.2.6 and 5.2.10, although the difference was not that significant on these servers: The PHP 5.2.10 server did run with date_default_timezone_set ("only") twice as fast as without. The 5.2.6 server did 5 times faster with date_default_timezone_set. As you can see below, the 5.2.6-Windows machine did a LOT faster.

Of course these machines have completely different hardware and can not really be compared, but all show improved performance.

I checked PHP 4.4.9 on Windows (without date_default_timezone_set of course) and noticed that its as fast as PHP 5.2.6 with date_default_timezone_set.

The following script shows this:

# date_default_timezone_set(date_default_timezone_get());functiongetmicrotime()

{

list($usec,$sec) =explode(' ',microtime());

return ($sec.substr($usec,1,7));

}$start=mktime(0,0,0,1,1,2005);$end=mktime(0,0,0,1,1,2020);$nr=50000;$start_time=getmicrotime();

for($i=0;$i

}$end_time=getmicrotime();

echo"Time: ".($end_time-$start_time);// With date_default_timezone_set(): "Time: 0.379343986511"

// Without date_default_timezone_set(): "Time: 7.4971370697"?>

Note that the timezone is not changed, it is only set again. I really wonder why this makes such a big performance difference, but its good to know.

[#14]

ted dot chou12 at gmail dot com [2008-12-02 23:13:13]

Timezone using other approaches:

$time obtained from table below:

-25200|International Date Line (West) GMT-12|

-21600|Midway Island, Samoa GMT-11|

-18000|Hawaii, Honolulu GMT-10|

-14400|Alaska GMT-9|

-10800|Pacific Standard Time, US, Canada GMT-8|

-7200|British Columbia N.E., Santa Fe, Mountain Time GMT-7|

-3600|Central America, Chicago, Guatamala, Mexico City GMT-6|

0|US, Canada, Bogota, Boston, New York GMT-5|

+3600|Canada, Santiago, Atlantic Standard Time GMT-4|

+7200|Brazilia, Buenos Aires, Georgetown, Greenland GMT-3|

+10800|Mid-Atlantic GMT-2|

+14400|Azores, Cape Verde Is., Western Africa Time GMT-1|

+18000|London, Iceland, Ireland, Morocco, Portugal GMT|

+21600|Amsterdam, Berlin, Bern, Madrid, Paris, Rome, GMT+1|

+25200|Athens, Cairo, Cape Town, Finland, Greece, Israel GMT+2|

+28800|Ankara, Aden, Baghdad, Beruit, Kuwait, Moscow GMT+3|

+32400|Abu Dhabi, Baku, Kabul, Tehran, Tbilisi, Volgograd GMT+4|

+36000|Calcutta, Colombo, Islamabad, Madras, New Dehli GMT+5|

+39600|Almaty, Dhakar, Kathmandu, Colombo, Sri Lanka GMT+6|

+43200|Bangkok, Hanoi, Jakarta, Phnom Penh, Australia GMT+7|

+46800|Taipei, Beijing, Hong Kong, Singapore, GMT+8|

+50400|Seoul, Tokyo, Central Australia GMT+9|

+54000|Brisbane, Canberra, Guam, Melbourne, Sydney, GMT+10|

+57600|Magadan, New Caledonia, Solomon Is. GMT+11|

+61200|Auckland, Fiji, Kamchatka, Marshall, Wellington, GMT+12|

[#15]

jason at jasonpriem dot com [2008-11-11 20:29:01]

While it's easy to change timezones based on names or abbreviations, I haven't found any straightforward way of doing so using an offset integer.  This situation comes up if you're using AJAX to get information about a user's timezone; javascript's getTimezoneOffset() method just sends you an offset number. So, here's my clunky solution: an adaptation of chris' function at http://us.php.net/manual/en/function.timezone-name-from-abbr.php.

foreach ($abbrarrayas$abbr) {//echo $abbr."
";foreach ($abbras$city) {//echo $city['offset']." $offset
";if ($city['offset'] ==$offset) {// remember to multiply $offset by -1 if you're getting it from jsdate_default_timezone_set($city['timezone_id']);

returntrue;

}

}

}date_default_timezone_set("ust");

returnfalse;

}set_tz_by_offset(-1);?>

[EDIT BY thiago AT php DOT net: This code has contributions from iateadonut at gmail dot com]

[#16]

Rob Kaper [2008-07-15 01:46:56]

If you want users to choose their own timezones, here's some code that gets all available timezones but only uses one city for each possible value:

$timezones=DateTimeZone::listAbbreviations();$cities= array();

foreach($timezonesas$key=>$zones)

{

foreach($zonesas$id=>$zone)

{if (preg_match('/^(America|Antartica|Arctic|Asia|Atlantic|Europe|Indian|Pacific)\//',$zone['timezone_id'] ) )$cities[$zone['timezone_id']][] =$key;

}

}// For each city, have a comma separated list of all possible timezones for that city.foreach($citiesas$key=>$value)$cities[$key] =join(', ',$value);// Only keep one city (the first and also most important) for each set of possibilities.$cities=array_unique($cities);// Sort by area/city name.ksort($cities);?>

[#17]

PeerGoal.com [2007-02-12 04:21:36]

The problem:

date() [function.date]: It is not safe to rely on the system's timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/Los_Angeles' for 'PST/-8.0/no DST' instead

Of course this is a problem that recently surfaced since PHP5. Quick fix is to set your time zone, add this line to your php code:

date_default_timezone_set("America/Los_Angeles");

[#18]

davidn at datalinktech dot com dot au [2006-12-21 17:27:03]

Note that there may be some unexpected side-effects that result from using either set_default_timezone() or the putenv("TZ=...") workalike for earlier PHP versions.  ANY date formatted and output either by PHP or its apache host process will be unconditionally expressed in that timezone.

[red. That is only true for the putenv() hack - Derick]

This does indeed include the web server's logs and other output files and reports which by default usually do not include any indication of timezone. This has a further side-effect on log processing and analysis, obviously.

mysql date_default_timezone_set,date_default_timezone_set相关推荐

  1. wordpress启动初始化过程

    2019独角兽企业重金招聘Python工程师标准>>> wordpress是免费开源的用php开发的博客平台,功能十分强大,中文友好,使用mysql数据库,安装非常方便.但是功能强大 ...

  2. destoon代码从头到尾捋一遍

    estoon® B2B网站管理系统(以下简称destoon)由西安嘉客信息科技有限责任公司独立研发并推出,对其拥有完全知识产权,中国国家版权局计算机软件著作权登记号:2009SR037570. 系统使 ...

  3. PHP基础(必须熟练掌握的基础)

    <?php/*** 三元运算符的应用*/ /* $a = 10; $b = 15; echo $a > $b ? 1 : 0; */ // 注:php7新添加的运算符比较运算符x<= ...

  4. PHP常用时间函数总结

    PHP常用时间函数总结: time time - 返回当前的 Unix 时间戳 说明 int time ( void ) 返回自从 Unix 纪元(格林威治时间 1970 年 1 月 1 日 00:0 ...

  5. 第一次sql注入的教训与思考

    sql注入实验 靶场在云演课堂web安全入门sql注入第一节 这课程排的我也不知道啥是sql注入,啥是文件上传漏洞了 文章目录 sql注入实验 sql注入是如何发生的 假设 从服务端代码入手 show ...

  6. 微擎inc.php 读不到,解读微擎之----bootstrap.inc.php

    加载各种静态资源,定义大量$_W下变量的值,判断是否安装微擎,设置phpini的值,$_W[]判断http发送的方式 '; //strpos("$atr","a" ...

  7. 【收藏】银联在线支付商户UPMP接口的使用和说明

    [转载]http://www.dodobook.net/php/1110 相关的文档可以参阅.http://202.101.25.178:8080/sim/docs/ 这个接口文档还是比较完备的,相信 ...

  8. PHP随手记1--内置函数date

    1. date_default_timezone_set date_default_timezone_set - 设定用于一个脚本中所有日期时间函数的默认时区 在php中只用 mktime() 函数时 ...

  9. PHPCMS V9 框架代码分析(入口程序)

    PHPCMS是采用MVC设计模式开发,基于模块和操作的方式进行访问,采用单一入口模式进行项目部署和访问,无论访问任何一个模块或者功能,只有一个统一的入口. 入口程序是在前期处理用户请求的引导程序.它是 ...

  10. PHPCMS后台框架实现思路

    PHPCMS后台框架实现思路[原创] 时间 2014-11-27 10:12:19 极客头条 原文  http://blogs.zmit.cn/3589.html 1.打开后台入口文件admin.ph ...

最新文章

  1. Windows or Linux
  2. 《疯狂Java讲义》9
  3. 动态更改echarts 高度_结合Echarts、Ajax技术实现可视化大屏监控 3D
  4. 为CEDIT添加有颜色的边框
  5. 我的计算机用户账户logo,UserAccountControl
  6. 签名验签服务器性能测试,签名验签服务器 功率
  7. [转贴]SQL2005数据类型
  8. LRN局部响应归一化
  9. 浅析小米登录/注册页面(原生)
  10. chrome浏览器打开axure原型图的方法
  11. 生存分析-Cox回归模型
  12. Android通知栏图标显示网络图片
  13. springboot整合xxl-job
  14. C++ GBD调试
  15. YiLu代理中住宅IP代理和数据中心/机房IP代理分析及对比
  16. iOS 苹果2.1大礼包回复模版-guideline 2.1 Information Needed
  17. Maglev: 一个快速、可靠的基于软件的网络负载均衡器(翻译)
  18. LaTex 希腊字母、数学符号、公式换行
  19. buildroot快速入门
  20. 如何能够让博客被百度等搜索到

热门文章

  1. 2.RabbitMQ实战 --- 理解消息通信
  2. 30.卷1(套接字联网API)---客户/服务器程序设计规范
  3. 7. 代码中特殊的注释技术——TODO、FIXME和XXX的用处
  4. java中float double利用BigDecimal运算
  5. 【问题】ajax两种传递id值方式的区别
  6. IOS 拉伸图片(封装)
  7. freemarker在线编辑
  8. VirtualBox - 虚拟机下主机与虚拟机、虚拟机与虚拟机之间通信配置
  9. Razor基础语法简介
  10. 如何使用Java代码将GBK编码格式的工程转换为UTF-8编码格式的工程