所以我检查了supported time zones in PHP列表,我想知道如何将它们包含在date()中;功能?谢谢!
我不想要一个默认时区,每个用户都有他们的时区存储在数据库中,我拿用户的时区并使用它。怎么样?我知道如何从数据库中获取它,而不是如何使用它。
对于这样的任务,你应该真正使用PHP DateTime类。请忽略所有建议您使用date()或日期set_time_zone的答案,它只是糟糕和过时。
我将使用伪代码进行演示,因此请尝试调整代码以满足您的需求。
假设变量$ tz包含有效时区的字符串名称,变量$ timestamp包含您希望根据时区格式化的时间戳,代码将如下所示:
$tz = 'Europe/London';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
echo $dt->format('d.m.Y, H:i:s');
DateTime类功能强大,并且要掌握它的所有功能 - 你应该花一些时间在php.net上阅读它。要完全回答您的问题 - 是的,您可以动态调整时区参数(在从db读取的每次迭代中,您可以创建一个新的DateTimeZone()对象)。
如果我理解正确,你需要先设置时区,如:
date_default_timezone_set('UTC');
而且你可以使用日期功能:
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
请使用DateTime class,因为它支持时区。与date()
相当的DateTime是DateTime::format
。
对于DateTime来说,一个非常有用的包装是Carbon - 绝对可以看一看。
您希望以UTC格式存储在数据库中并在应用程序级别进行转换。
它应该是这样的:
date_default_timezone_set('America/New_York');
answer above让我跳过了一些箍/陷阱,所以只需发布适合我的清洁代码:
$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('America/New_York'));
$dt->setTimestamp(123456789);
echo $dt->format('F j, Y @ G:i');
试试这个。您可以传递unix时间戳或日期时间字符串
public static function convertToTimezone($timestamp, $fromTimezone, $toTimezone, $format='Y-m-d H:i:s')
{
$datetime = is_numeric($timestamp) ?
DateTime::createFromFormat ('U' , $timestamp, new DateTimeZone($fromTimezone)) :
new DateTime($timestamp, new DateTimeZone($fromTimezone));
$datetime->setTimezone(new DateTimeZone($toTimezone));
return $datetime->format($format);
}
我已经创建了这个非常简单的功能,它就像一个魅力:
function ts2time($timestamp,$timezone){ /* input: 1518404518,America/Los_Angeles */
$date = new DateTime(date("d F Y H:i:s",$timestamp));
$date->setTimezone(new DateTimeZone($timezone));
$rt=$date->format('M d, Y h:i:s a'); /* output: Feb 11, 2018 7:01:58 pm */
return $rt;
}
这在2019年完美地运作:
date('Y-m-d H:i:s',strtotime($date. ' '.$timezone));
您可以在date_default_timezone_set函数,date_default_timezone_set(SOME_PHP_VARIABLE)中替换数据库值;但只需要处理与时区相关的确切值。