如何在 PHP 中获取本地时区?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8648973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:10:08  来源:igfitidea点击:

How to get local timezone in PHP?

phpdatetimedatetimetimezone

提问by Steve

I'm using the date("D, m/d/Y h:i:s A T")function call to get current date time but returned time is different to the time I get when I make date in linux bash command (local time is in CSTand php date function returns time in UTC). I've tried using $timezone = @system("date +%Z",$retval);to get timezone in an attempt to set local timezone using date_default_timezone_set()function. But CSTseems not a valid timezone_identifier.

我正在使用date("D, m/d/Y h:i:s A T")函数调用来获取当前日期时间,但返回的时间与我在 linux bash 命令中创建日期时得到的时间不同(本地时间在CST 中,php date 函数以UTC返回时间)。我尝试使用$timezone = @system("date +%Z",$retval);获取时区以尝试使用date_default_timezone_set()函数设置本地时区。但CST似乎不是有效的 timezone_identifier。

In short, I just need to get the same date and time as local datetime.

简而言之,我只需要获得与本地日期时间相同的日期和时间。

回答by Christopher Manning

Use a timezone from http://php.net/manual/en/timezones.php

使用来自http://php.net/manual/en/timezones.php的时区

So, for CST use:

因此,对于 CST 使用:

<?php
date_default_timezone_set("America/Chicago");

If you only have the timezone abbreviation and not the timezone id then use:

如果您只有时区缩写而不是时区 ID,则使用:

<?php
date_default_timezone_set(timezone_name_from_abbr("CST"));

回答by Jason McCreary

Although the system and PHP shouldbe on the same timezone, read the docs for date_default_timezone_set()to set the timezone manually.

尽管系统和 PHP应该在同一时区,但请阅读文档date_default_timezone_set()以手动设置时区。

Note that CST is nota valid timezone setting. Find a valid timezonefor your location.

请注意,CST不是有效的时区设置。为您所在的位置找到一个有效的时区

回答by Steve

I think I've found a better function: timezone_name_from_abbr()

我想我找到了一个更好的功能: timezone_name_from_abbr()