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.
The answer above caused me to jump through some hoops/gotchas, so just posting the cleaner code that worked for me:
Use the DateTime class instead, as it supports timezones. The DateTime equivalent of
date()
isDateTime::format
.An extremely helpful wrapper for DateTime is Carbon - definitely give it a look.
You'll want to store in the database as UTC and convert on the application level.
If I understood correct,You need to set time zone first like:
And than you can use date function:
I have created this very straightforward function, and it works like a charm:
It should like this:
For such 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.
I'll use pseudocode to demonstrate, so try to adjust the code to suit your needs.
Assuming that variable $tz contains string name of a valid time zone and variable $timestamp contains the timestamp you wish to format according to time zone, the code would look like this:
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).