How to display local time with PHP

2019-06-28 06:11发布

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?

标签: php timezone
5条回答
smile是对你的礼貌
2楼-- · 2019-06-28 06:24

You can use the date function to offset GMT

查看更多
该账号已被封号
3楼-- · 2019-06-28 06:25

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!

查看更多
Evening l夕情丶
4楼-- · 2019-06-28 06:40

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楼-- · 2019-06-28 06:42

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

查看更多
在下西门庆
6楼-- · 2019-06-28 06:47

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")
查看更多
登录 后发表回答