How to display local time with PHP

本小妞迷上赌 提交于 2019-12-23 13:06:28

问题


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?


回答1:


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:- http://us2.php.net/manual/en/function.date-default-timezone-set.php




回答2:


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



回答3:


You can use the date function to offset GMT




回答4:


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>



回答5:


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!



来源:https://stackoverflow.com/questions/1466998/how-to-display-local-time-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!