Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing PHP default timezone not working

Tags:

date

timezone

php

I am trying to have a line of code added to an html document that is preceded by the time. I want the time zone to be relative to me, however I cannot change it from the default UTC. I have changed in the php.ini file to PST as well as using date_default_timezone_set('America/Los_Angeles'); and yet it still prints the time 7 hours ahead of my timezone. Heres the code that deals with the time:

session_start();
if(isset($_SESSION['name']))
{
    date_default_timezone_set('America/Los_Angeles');

    $msg = $_POST['text'];

    $fo = fopen("log.html", 'a');
    fwrite($fo, "<div class=msgln>(".date("g:i A").") <b  style=color:red;>".$_SESSION['name']."</b>: ".stripslashes(htmlspecialchars($msg))."<br></div>
    ");
    fclose($fo);
}
like image 539
Xander Luciano Avatar asked Sep 01 '26 06:09

Xander Luciano


2 Answers

Servers should be set to UTC, and you should not be looking to change the default. Instead, what you want to do is create a DateTime object based on the time, then convert it to the timezone you want, and display.

$now = new DateTime();
$now->setTimezone(new DateTimeZone('America/Los_Angeles'));
echo $now->format('g:i A');

I don't know if your format string is valid or not, but the format method is suppossed to be compatible with that accepted by the date() function you were using in your original example.

like image 184
gview Avatar answered Sep 03 '26 20:09

gview


First make sure you're using a valued timezone. You can find a list of supported timezones in the PHP docs.

The second problem is using date() without specifying the timestamp. This defaults to the timestamp produced by time() which (based on a comment in the documentation) is UTC time. You'll either have to use strftime() or manually subtract the difference from UTC.

like image 33
BrianS Avatar answered Sep 03 '26 22:09

BrianS