Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

timezone - converting timestamp to local time with PHP

I'm trying to get a timestamp in local time with PHP from a mySQL database and I'm gettin errors, the original code that I was using was this, that obviously returned the UTC time:

$timestamp = strtotime($row['created']);
$dt = date('d/m/Y H:i', $timestamp);

Now searching in previous answers I've found this code:

$date = /* SELECT date FROM database */;
$usersTimezone = new DateTimeZone('America/Vancouver');
$l10nDate = new DateTime($date);
$l10nDate->setTimeZone($usersTimezone);
echo $l10nDate->format('Y-m-d H:i:s');

But I couldn't make it work... I tried adding

date_default_timezone_set('America/Vancouver'); 

too, but it dind't work neither... and I only did minimum changes because I want to save it in a variable not echo it. Also, looking that information in that previous answer, I don't know neither if I can convert any UTC timestamp, or I have to insert the record in my timezone previously to can convert it back later.

Thanks for your time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By default DateTime::construct uses your local timezone. However your time is in UTC, so you need to tell the constructor that, and then modify the timezone:

$date = '2018-10-13 00:00:00';
$l10nDate = new DateTime($date, new DateTimeZone('UTC'));
$l10nDate->setTimeZone(new DateTimeZone('America/Vancouver'));
echo $l10nDate->format('Y-m-d H:i:s');

Output

2018-10-12 17:00:00

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...