Home >Backend Development >PHP Tutorial >Solution to the error of using the date function to obtain the current time in PHP_PHP Tutorial
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?
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.