百科狗-知识改变命运!

date_default_timezone_get() - php 日期时间函数

是丫丫呀2年前 (2023-11-21)阅读数 25#技术干货
文章标签时区

date_default_timezone_get()

(PHP 5 >= 5.1.0, PHP 7)

取得一个脚本中所有日期时间函数所使用的默认时区

说明

date_default_timezone_get(void): string

本函数返回默认时区,使用如下“假定”的顺序:

  • 用date_default_timezone_set()函数设定的时区(如果设定了的话)

  • 仅仅在 PHP 5.4.0 之前:TZ环境变量(如果非空)

  • date.timezone配置选项(如果设定了的话)

  • 仅仅在 PHP 5.4.0 之前:查询操作系统主机(如果操作系统支持并允许)。 This uses an algorithm that has toguessthe timezone. This is by no means going to work correctly for every situation. A warning is shown when this stage is reached. Do not rely on it to be guessed correctly, and setdate.timezoneto the correct timezone instead.

  • 如果以上选择都不成功,date_default_timezone_get()会则返回UTC的默认时区。

返回值

返回一个string。

更新日志

版本说明
5.4.0不再使用TZ来推测时区。
5.4.0不再根据操作系统的信息来推测时区,因为这是不可靠的。

范例

获取默认时区


以上例程的输出类似于:

date_default_timezone_set: Europe/London
date.timezone: Europe/London

获取一个时区的简写

date_default_timezone_get() - php 日期时间函数


以上例程会输出:

America/Los_Angeles => America/Los_Angeles => PST

参见

  • date_default_timezone_set()设定用于一个脚本中所有日期时间函数的默认时区
  • 所支持的时区列表
Please note that on Debian/Ubuntu this function will return the system timezone defined in /etc/localtime if date.timezone is not defined, even with PHP 5.4+
See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=673763#10
In my case, I'm not sure I can guess the correct timezone any better than PHP and it's no where near important enough to nag the user, so...

Please note that "Damien dot Garrido dot Work at gmail dot com" code is wrong, the third parameter of sprintf must be divided by 60.
This is the corrected function:

To get offset string from offset:

Output:
offset: +14:00
offset: -10:00
For the reason that date_default_timezone_get() throws an error when the timezone isn't set in php.ini and then returns a default chosen by the system (rather than returning false to indicate to the script that a timezone hasn't been set), I've found that the following works when you want a script to detect when the ini value has not been set and want the script itself to choose a default in that case, while still allowing bootstrap scripts to set their own default using date_default_timezone_set().

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)
{if $zbp->Config('yd1125')->foot}