栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将php日期格式转换为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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/430490.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号