Search code examples
phpdatetimezone

PHP date() with timezone?


So I've checked the list of supported time zones in PHP and I was wondering how could I include them in the date() function? Thanks!

I don't want a default timezone, each user has their timezone stored in the database, I take that timezone of the user and use it. How? I know how to take it from the database, not how to use it, though.


Solution

  • For such a task, you should really be using PHP's DateTime class. Please ignore all of the answers advising you to use date() or date_set_time_zone, it's simply bad and outdated.

    $dt = new DateTime("now", new DateTimeZone('Europe/London')); 
    echo $dt->format('d.m.Y, H:i:s');
    

    DateTime class is powerful, and to grasp all of its capabilities - you should devote some of your time reading about it at php.net. To answer your question fully - yes, you can adjust the time zone parameter dynamically (on each iteration while reading from DB, you can create a new DateTimeZone() object).