我是 php 新手。我想编写一个函数,我需要用户以包括 DST 在内的任何日期格式输入日期,输入 GMT 格式,然后再输入原始输入格式。请任何人帮助我。
38456 次
3 回答
30
虽然 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
于 2011-03-28T04:58:25.427 回答
4
于 2011-03-28T04:45:52.143 回答
0
// 将本地时间转换为gmt
public function convertTime($timezone,$time){
$selectedtime = date("Y-m-d H:i",strtotime($time));
$date = new DateTime($selectedtime, new DateTimeZone($timezone));
$date->setTimezone(new DateTimeZone('GMT'));
$convertedtime = strtotime($date->format('Y-m-d H:i'));
return $convertedtime;
}
于 2016-03-01T11:43:28.650 回答