PHP - date() vs. date.timezone / date_default_time

2019-04-07 18:08发布

问题:

I've just got a new computer, and I've been setting up PHP/MySQL/databases etc... I think I'm just about there, except it's thrown this curveball. My login script was working fine, but now it's spitting the following warning (which messes up the JSON).

Warning: date() [function.date]: It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting 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 'Antarctica/Macquarie' for 'EST/10.0/no DST' instead in .../php/login.php on line 47

My code obviously uses date() and is working in the live version and on the old machine. I get two warnings for the following two lines of code:

$date = date("ymd");

$this_year = date("y");

My research (see here) suggests that the behaviour of these functions depends on php.ini .

So should I change php.ini on the new machine, or am I using some kind of deprecated method, and should I ditch date() altogether?

Thanks.

回答1:

You don't need to change the php.ini file if you use date_default_timezone_set(). Just set it to the timezone you will be working in.

Something like this should go in a config file or on the page where you're working with dates (if it is only one page):

date_default_timezone_set('America/Los_Angeles');


回答2:

It's not an exception, it's a warning that is probably popping up now because your error reporting settings on the new machine are different from the old one.

I would suggest to follow the suggestion in the warning, and use date_default_timezone_set() to set a time-zone in the scripts where you need it.



回答3:

First, you are although it may know, this solves the problem.

date_default_timezone_set('Your/Timezone');

If you want to configure in php.ini, modify below

[Date]
; ...
; ...
date.timezone = Your/Timezone


回答4:

You do not have to change the php.ini.

However, if you have a timezone which you will use for most of your your php files adding the following line to your php.ini should do the trick.

date.timezone = "Your/Timezone"

In my case I added the following line to php.ini. Personally, I prefer to keep all our servers at UTC timezone.

date.timezone = "UTC"