加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

如何将php日期格式转换为GMT,反之亦然?

发布时间:2020-12-13 21:28:12 所属栏目:PHP教程 来源:网络整理
导读:我是php的新手. 我想编写一个函数,我需要用户以任何日期格式输入日期,包括DST,GMT格式,然后再回到原来输入的格式.请任何机构帮助我. 解决方法 虽然gmdate功能可用.如果您使用的是 PHP 5.2或更高版本,请考虑使用 DateTime对象. 这是切换到GMT的代码 $date = n
我是php的新手.
我想编写一个函数,我需要用户以任何日期格式输入日期,包括DST,GMT格式,然后再回到原来输入的格式.请任何机构帮助我.

解决方法

虽然gmdate功能可用.如果您使用的是 PHP 5.2或更高版本,请考虑使用 DateTime对象.

这是切换到GMT的代码

$date = new DateTime();
$date->setTimezone(new DateTimeZone('GMT'));

并返回默认时区…

$date = new DateTime('2011-01-01',new DateTimeZone('GMT'));
$date->setTimezone(new DateTimeZone(date_default_timezone_get()));

使用DateTime对象可以创建日期时间,就像过程函数一样,除了保留对实例的引用.

例如

// Get a reference to Christmas of 2011,at lunch time.
$date = new DateTime('2011-12-25 13:00:00');

// Print the date for people to see,in whatever format we specify.
echo $date->format('D jS M y');

// Change the timezone to GMT.
$date->setTimezone(new DateTimeZone('GMT'));

// Now print the date/time it would in the GMT timezone
// as opposed to the default timezone it was created with.
echo $date->format('Y-m-d H:i:s');

// Just to show of some more,get the previous Sunday
$date->modify('previous Sunday');

你可以使用很多函数,它们比程序函数更具可读性.

从时区转换为GMT的明确示例

$melbourne = new DateTimeZone('Australia/Melbourne');
$gmt = new DateTimeZone('GMT');

$date = new DateTime('2011-12-25 00:00:00',$melbourne);
$date->setTimezone($gmt);
echo $date->format('Y-m-d H:i:s');
// Output: 2011-12-24 13:00:00
// At midnight on Christmas eve in Melbourne it will be 1pm on Christmas Eve GMT.

echo '<br/>';

// Convert it back to Australia/Melbourne
$date->setTimezone($melbourne);
echo $date->format('Y-m-d H:i:s');

使用您的亚洲/加尔各答到美国/纽约

date_default_timezone_set('Asia/Kolkata');
$date = new DateTime('2011-03-28 13:00:00');
$date->setTimezone(new DateTimeZone('America/New_York'));
echo $date->format("Y-m-d H:i:s");
//Outputs: 2011-03-28 03:30:00

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读