Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timezone conversion in php

Can anyone suggest an easy method to convert date and time to different timezones in php?

like image 704
raki Avatar asked Mar 24 '10 06:03

raki


People also ask

How can we convert the time zones using php?

php $datetime = date("Y-m-d H:i:s"); $utc = new DateTime($datetime, new DateTimeZone('UTC')); $utc->setTimezone(new DateTimeZone('America/Sao_Paulo')); echo $utc->format('Y-m-d H:i:s'); ?>

What timezone does php use?

The default timezone for PHP is UTC regardless of your server's timezone. This is the timezone used by all PHP date/time functions in your scripts.

How do I set default timezone?

The date_default_timezone_set() function sets the default timezone used by all date/time functions in the script.


1 Answers

You can use the datetime object or their function aliases for this:

Example (abridged from PHP Manual)

date_default_timezone_set('Europe/London');  $datetime = new DateTime('2008-08-03 12:35:23'); echo $datetime->format('Y-m-d H:i:s') . "\n"; $la_time = new DateTimeZone('America/Los_Angeles'); $datetime->setTimezone($la_time); echo $datetime->format('Y-m-d H:i:s'); 

Edit regarding comments

but i cannt use this method because i need to show date in different time zones as the user login from different locations

That's not a problem. When a user logs in, you determine his timezone and set it to your DateTime object just like shown. I'm using a similar approach in one of my projects and it works like a charm.

in the database i need to get the dates in any single timezone, then only it can be processed properly

You store the time either as a timestamp or a datetime in one timezone. When you query a DateTime field, you either convert the time in a DateTime object to this timezone or - if your db supports it - query with the selected timezone.

like image 123
Gordon Avatar answered Sep 22 '22 01:09

Gordon