PHP date()与时区? [英] PHP date() with timezone?

查看:126
本文介绍了PHP date()与时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我检查了 PHP支持的时区列表,我想知道如何将它们包含在 date()函数中?
谢谢!

So I've checked the list of supported time zones in PHP and I was wondering how could I include them in the date() function? Thanks!

我不需要默认时区,每个用户的时区都存储在数据库中,我使用该用户的时区并使用它。怎么样?我知道如何从数据库中获取它,而不是如何使用它。

I don't want a default timezone, each user has their timezone stored in the database, I take that timezone of the user and use it. How? I know how to take it from the database, not how to use it, though.

推荐答案

对于这样的任务,您应该使用PHP的DateTime类。请忽略所有建议您使用date()或date_set_time_zone的答案,这太糟糕了并且已经过时了。

For such task, you should really be using PHP's DateTime class. Please ignore all of the answers advising you to use date() or date_set_time_zone, it's simply bad and outdated.

我将使用伪代码进行演示,因此请尝试调整满足您需要的代码。

I'll use pseudocode to demonstrate, so try to adjust the code to suit your needs.

假设变量$ tz包含有效时区的字符串名称,变量$ timestamp包含您希望根据时区格式化的时间戳,代码如下:

Assuming that variable $tz contains string name of a valid time zone and variable $timestamp contains the timestamp you wish to format according to time zone, the code would look like this:

$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()对象)。

DateTime class is powerful, and to grasp all of its capabilities - you should devote some of your time reading about it at php.net. To answer your question fully - yes, you can adjust the time zone parameter dynamically (on each iteration while reading from db, you can create a new DateTimeZone() object).

这篇关于PHP date()与时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆