Home  >  Article  >  Backend Development  >  Solution to the error of using the date function to obtain the current time in PHP_PHP Tutorial

Solution to the error of using the date function to obtain the current time in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:00:07731browse

I am new to building a website in PHP and want to get the current time on the page. Anyone who has learned programming knows to use the time function date(). First use this function to format a local time/date. First write a test code. The result The output time is 8 hours less than the actual time. What is the reason?

Copy the code The code is as follows:

< ?php
echo date('Y-m-d H:i:s');
?〉

Output current time: 2008-10-12 02:32:17
Strange Yes, the actual time is: 2008-10-12 10:32:17

Could it be that PHP’s date() time is incorrect and is 8 hours short?
Look again at the "Example 1. date() example" in the PHP manual. There is an additional time zone setting in the first line
// Set the default time zone to be used. Available since PHP 5.1
date_default_timezone_set('UTC');

It turns out that since php5.1., the date.timezone option has been added to php.ini. It is turned off by default, that is, the time displayed (no matter what php command is used) is Greenwich Mean Time, and Beijing time is exactly 8 hours different.

How to set up the correct PHP time?

1. Modify php.ini. Open php.ini and search for date.timezone. Remove the semicolon = in front and add Asia/Shanghai at the end. Just restart the apache server - the disadvantage is that if the program
is placed on someone else's server, php cannot be modified. .ini, then there is nothing you can do.

2. Add the time initialization statement in the program, that is: "date_default_timezone_set("Asia/Shanghai"); "This can be set arbitrarily by the programmer, mine recommend.
Time zone identifier, available values ​​in mainland China are: PRC, Asia/Chongqing, Asia/Shanghai, Asia/Urumqi (in order China, Chongqing, Shanghai, Urumqi), Etc/GMT-8, Asia/Harbin

Available in Hong Kong and Taiwan: Asia/Macao, Asia/Hong_Kong, Asia/Taipei (Macau, Hong Kong, Taipei in order) and Singapore: Asia/Singapore
In this way, the output is Beijing time.

More detailed time zone codes, time zone codes, time zone index codes, timezone_identifier, can be found on the official website.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/328097.htmlTechArticleI am new to PHP and want to get the current time on the page. Anyone who has learned programming knows to use the time function date (), first use this function to format a local time/date, first write a test code...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn