Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...