[php] 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.

This question is related to php date timezone

The answer is


Try this. You can pass either unix timestamp, or datetime string

public static function convertToTimezone($timestamp, $fromTimezone, $toTimezone, $format='Y-m-d H:i:s') 
    {
        $datetime = is_numeric($timestamp) ?
                    DateTime::createFromFormat ('U' , $timestamp, new DateTimeZone($fromTimezone)) :
                    new DateTime($timestamp, new DateTimeZone($fromTimezone));

        $datetime->setTimezone(new DateTimeZone($toTimezone));

        return $datetime->format($format);
    }

I have created this very straightforward function, and it works like a charm:

function ts2time($timestamp,$timezone){ /* input: 1518404518,America/Los_Angeles */            
        $date = new DateTime(date("d F Y H:i:s",$timestamp));
        $date->setTimezone(new DateTimeZone($timezone));
        $rt=$date->format('M d, Y h:i:s a'); /* output: Feb 11, 2018 7:01:58 pm */
        return $rt;
    }

The answer above caused me to jump through some hoops/gotchas, so just posting the cleaner code that worked for me:

$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('America/New_York'));
$dt->setTimestamp(123456789);

echo $dt->format('F j, Y @ G:i');

It should like this:

date_default_timezone_set('America/New_York');

U can just add, timezone difference to unix timestamp. Example for Moscow (UTC+3)

echo date('d.m.Y H:i:s', time() + 3 * 60 * 60);

Not mentioned above. You could also crate a DateTime object by providing a timestamp as string in the constructor with a leading @ sign.

$dt = new DateTime('@123456789');
$dt->setTimezone(new DateTimeZone('America/New_York'));
echo $dt->format('F j, Y - G:i');

See the documentation about compound formats: https://www.php.net/manual/en/datetime.formats.compound.php


Use the DateTime class instead, as it supports timezones. The DateTime equivalent of date() is DateTime::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:

date_default_timezone_set('UTC');

And than you can use date function:

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

this works perfectly in 2019:

date('Y-m-d H:i:s',strtotime($date. ' '.$timezone)); 

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:

$tz = 'Europe/London';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
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).


You can replace database value in date_default_timezone_set function, date_default_timezone_set(SOME_PHP_VARIABLE); but just needs to take care of exact values relevant to the timezones.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to timezone

How to set the timezone in Django? How to convert Moment.js date to users local timezone? What does this format means T00:00:00.000Z? How do I get the current timezone name in Postgres 9.3? MySQL JDBC Driver 5.1.33 - Time Zone Issue Python get current time in right timezone Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings PHP date() with timezone? How to store a datetime in MySQL with timezone info Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST