Rik Heywood
Rik Heywood

Reputation: 13972

How to display local time with PHP

Our server is set to GMT time so the hour does not keep jumping around in spring and autumn. However, during summer time, it is annoying that all the times are displayed an hour out.

How do I get and display the time, taking into account the local timezone in PHP (especially when the server thinks the local timezone is GMT).

or, How do I know if an area is using "summer time" at the moment?

or, How do I display a GMT time stamp or a different timezone?

Upvotes: 5

Views: 17056

Answers (5)

david72
david72

Reputation: 7297

Easiest way to display local time is to use JavaScript:

<?php

// Get unix time from database
$seconds = .....;

?>
<html>
  <head>
    <script type="text/javascript">
        function showLocalTime()
        {
            var seconds = <?=$seconds;?>;
            var date = new Date(seconds*1000);
            var hours = date.getHours();
            var minutes = "0" + date.getMinutes();
            var seconds = "0" + date.getSeconds();
            var formattedTime = hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);

            document.getElementById("local_time").innerHTML = "Local Time: " + formattedTime;
        }
  </script>

  </head>

  <body onload="showLocalTime()">
    <h2 id="local_time"> Local Time: </h2>
  </body>

</html>

Upvotes: -1

jimyi
jimyi

Reputation: 31191

You could add this line in PHP:

putenv("TZ=US/Eastern");

And every subsequent call to time()/date() will give you the time in your time zone.

List of time zones

This code will display the current time in the Eastern time zone (US):

putenv("TZ=US/Eastern");
date("h:i:s")

Upvotes: 4

Rik Heywood
Rik Heywood

Reputation: 13972

Actually, I think I may have found the answer I need...

date_default_timezone_set()
// Sets the default timezone used by all date/time functions in a script 

The PHP manual entry is here:- https://www.php.net/manual/en/function.date-default-timezone-set.php

Upvotes: 4

Ryan Kearney
Ryan Kearney

Reputation: 1071

You can use the date function to offset GMT

Upvotes: 0

Evernoob
Evernoob

Reputation: 5561

get the date/time and first check to see if the month (split on dashes if its a DATETIME field) is a 'summer month', or a month that will cause the time to be an hour out.

If so, convert it to a unix timestamp. Then, add (or minus, whichever way it is out) 60 * 60 (60 mins) to the timestamp and convert into a human readable format.

Problem solved!

Upvotes: -3

Related Questions