PHP date() with timezone?

PhpDateTimezone

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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).

Solution 2 - Php

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');

Solution 3 - 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.

Solution 4 - Php

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');

Solution 5 - Php

It should like this:

date_default_timezone_set('America/New_York');

Solution 6 - Php

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);

Solution 7 - Php

this works perfectly in 2019:

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

Solution 8 - Php

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);
    }

Solution 9 - Php

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;
    }

Solution 10 - Php

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

Solution 11 - Php

I have tried the answers based on the DateTime class. While they are working, I found a much simpler solution that makes a DateTime object timezone aware at the time of creation.

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

This returns the current local time in Jakarta, Indonesia.

Solution 12 - Php

If you use Team EJ's answer, using T in the format string for DateTime will display a three-letter abbreviation, but you can get the long name of the timezone like this:

$date = new DateTime('2/3/2022 02:11:17');
$date->setTimezone(new DateTimeZone('America/Chicago'));

echo "\n" . $date->format('Y-m-d h:i:s T');
/* Displays 2022-02-03 02:11:17 CST "; */

$t = $date->getTimezone();
echo "\nTimezone: " . $t->getName();
/* Displays Timezone: America/Chicago */

Solution 13 - Php

$now = new DateTime();
$now->format('d-m-Y H:i:s T')

Will output:

29-12-2021 12:38:15 UTC

Solution 14 - Php

Based on other answers I built a one-liner, where I suppose you need current date time. It's easy to adjust if you need a different timestamp.

$dt = (new DateTime("now", new DateTimeZone('Europe/Rome')))->format('d-m-Y_His');

Solution 15 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2917204View Question on Stackoverflow
Solution 1 - PhpN.B.View Answer on Stackoverflow
Solution 2 - PhpSuresh KamrushiView Answer on Stackoverflow
Solution 3 - PhpceejayozView Answer on Stackoverflow
Solution 4 - PhpAndrewView Answer on Stackoverflow
Solution 5 - Phpuser3049608View Answer on Stackoverflow
Solution 6 - PhpMike.StanleyView Answer on Stackoverflow
Solution 7 - PhpemmanuelView Answer on Stackoverflow
Solution 8 - PhpdzonaView Answer on Stackoverflow
Solution 9 - PhpShatadip MajumderView Answer on Stackoverflow
Solution 10 - PhpTeam EJView Answer on Stackoverflow
Solution 11 - PhpKalyan Srinivas LimkarView Answer on Stackoverflow
Solution 12 - PhpBob RayView Answer on Stackoverflow
Solution 13 - PhpYhensel Benitez TapiaView Answer on Stackoverflow
Solution 14 - PhpKar.maView Answer on Stackoverflow
Solution 15 - PhpYatin TrivediView Answer on Stackoverflow