Can anyone suggest an easy method to convert date and time to different timezones in 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'); ?>
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.
The date_default_timezone_set() function sets the default timezone used by all date/time functions in the script.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With