简体   繁体   中英

PHP date_default_timezone_set() function on Localhost

I have a question regarding PHP date_default_timezone_set() function.

I'm trying to use this function to set my own time zone (Africa/Cairo) for my PHP code and it's not working at all.

I'm working on Localhost and I don't know if this note is important or not.

Anyways, This is my code to grab the UNIX timestamp:

$dateTime =  time();

And this is the code for the timezone:

date_default_timezone_set('Africa/Cairo');

Also tried this one and the same not working:

ini_set('date.timezone', 'Africa/Cairo');

And I'm using this code to show the date and time:

$date = new DateTime("@$dateTime");

echo "Date: " . $date->format("Y-m-d") . "<br> Time: " . $date->format("h:i:s A");

This always giving me wrong time, The date is fine.

Kindly I need your advice if this code is the right way to do this or there are another advanced and accurate code for this operation.

Thanks Guys

Use DateTime without any parameters...

$date = new DateTime();

If you pass a unix timestamp you will get the time in UTC as that is what a unix timestamp is relative to.

Clearly there are many people suffering from timezone problems.

Finally I found these functions date_add() and date_sub() which add or subtract any value on your date or time.

Example:

date_add($date , date_interval_create_from_date_string("7 Hours"));

This will simply add 7 hours to your time. Check out full date_add() and date_sub() references on php.net.

These functions is like a saver sometimes but sure it's better to find your own timezone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM