如何在 PHP 中获得格林威治标准时间?

2022-01-16 00:00:00 timezone php

我有一个设置为 EST 的服务器,并且数据库中的所有记录都设置为 EST.我想知道如何将其设置为 GMT.我想为我的用户提供时区选项.

I have a server which is set to EST, and all records in the database are set to EST. I would like to know how to set it to GMT. I want to offer a time zone option to my users.

推荐答案

无论服务器在哪个 GMT 时区,这里都有一个非常简单的方法来获取任何时区的时间和日期.这是通过 time()gmdate() 函数完成的.gmdate() 函数通常为我们提供 GMT 时间,但是通过使用 time() 函数我们可以得到 GMT+N 或 GMT-N,这意味着我们可以获取任何 GMT 时区的时间.

No matter in which GMT time zone the server is, here is an extremely easy way to get time and date for any time zone. This is done with the time() and gmdate() functions. The gmdate() function normally gives us GMT time, but by doing a trick with the time() function we can get GMT+N or GMT-N, meaning we can get the time for any GMT time zone.

例如,如果你必须得到 GMT+5 的时间,你可以这样做

For example, if you have to get the time for GMT+5, you can do it as follows

<?php 
  $offset=5*60*60; //converting 5 hours to seconds.
  $dateFormat="d-m-Y H:i";
  $timeNdate=gmdate($dateFormat, time()+$offset);
?>

现在,如果您必须获取 GMT-5 的时间,您可以从 time() 中减去偏移量,而不是添加到偏移量中,如下例中我们获取GMT-4 时间

Now if you have to get the time for GMT-5, you can just subtract the offset from the time() instead of adding to it, like in the following example where we are getting the time for GMT-4

<?php 
  $offset=4*60*60; //converting 4 hours to seconds.
  $dateFormat="d-m-Y H:i"; //set the date format
  $timeNdate=gmdate($dateFormat, time()-$offset); //get GMT date - 4
?>

相关文章