[英]PHP - How to change datetime from UTC when pulling data from MYSQL into JSON?
I am pulling some data from a MYSQL database in which I have a date-time that is stored in UTC, then converting everything into JSON. 我从MYSQL数据库中提取了一些数据,该数据库中有一个保存在UTC中的日期时间,然后将所有内容转换为JSON。 What I need to accomplish is that I want to show this datetime in UTC+3, not UTC.
我需要完成的是我想以UTC + 3(而不是UTC)显示此日期时间。
This is how I am doing everything: 这就是我所做的一切:
function getValues() {
$sth = mysql_query($query);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows['announcements'][] = $r;
}
print json_encode($rows);
}
This is the output I get (example): 这是我得到的输出(示例):
{
"announcements":[
{"id":"1","Title":"Title One","Details":"Detail of One","Submitter":"Alaa Alrufaie","DateSubmitted":"2016-03-06 17:03:48"},
{"id":"7","Title":"Title Seven","Details":"Detail of Seven","Submitter":"Alaa Alrufaie","DateSubmitted":"2016-03-06 17:23:44"}
]
}
How can I output the time in UTC+3 while maintaining this same JSON structure? 如何在保持相同JSON结构的同时在UTC + 3中输出时间?
You should make the change while reading the database result set: 您应该在读取数据库结果集时进行更改:
while($r = mysql_fetch_assoc($sth)) {
$r['DateSubmitted'] =
date("Y-m-d H:i:s", strtotime($r['DateSubmitted'].'+3 hours'));
$rows['announcements'][] = $r;
}
I would however add the time zone information to the date as well, so the consumer of the JSON data knows it is UTC+3. 但是,我也会在日期中添加时区信息,因此JSON数据的使用者知道它是UTC + 3。 For this you should use the ISO 8601 format , which has a
T
between date and time, and the additional time zone shift appended as +hh:mm
(the colon is optional): 为此,您应该使用ISO 8601格式 ,该格式在日期和时间之间有一个
T
,并且附加的时区偏移附加为+hh:mm
(冒号是可选的):
$r['DateSubmitted'] =
date("Y-m-d\TH:i:s+03:00", strtotime($r['DateSubmitted'].'+3 hours'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.