Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date and time to GMT and vice versa in PHP.....?

I have a PHP project where I need to show the time and date when the user1 sends a message to another user, user2. When the user2 opens this message time and date must be shown according to his timezone.

Since both users belong to different timezone, it shows the same date and time that USER1 entered.

For example : If User1 sends the message on 15-Feb-2011 at 11:30 AM on his timezone, and User2 opens this message then the date and time must shown according to his timezone. Lets say User2 belongs to India (GMT+5:30) then it show Message Sent at 15-Feb-2011, 04:30 PM.

But it is showing 15-Feb-2011, 11:30 AM that is wrong.

like image 417
Pushpendra Avatar asked Feb 15 '11 08:02

Pushpendra


3 Answers

Try this code:

$tmp_date = new Zend_Date();
$tmp_date->setTimezone( $user1_timezone );
$tmp_date->set( $date , $user1_date_format );
$tmp_date->setTimezone( $user2_timezone );
$user2_date = $tmp_date->toString( $user2_date_format );

I use this successfully to convert localtime to UTC.

Best Regards, SWilk

like image 163
SWilk Avatar answered Oct 13 '22 10:10

SWilk


You can use date_create and date_timezone_set. For example:

$mydate = date_create('2014-03-27 10:00', timezone_open('Europe/London'));
date_timezone_set($mydate, timezone_open('Europe/Athens'));
echo date_format($mydate, 'Y-m-d H:i:s') . "\n";

will output:

2014-03-27 12:00:00
like image 29
Fotis Avatar answered Oct 13 '22 11:10

Fotis


You can do this in MySQL as well:

SELECT CONVERT_TZ(your_column,"Europe/London","Europe/Paris") FROM table1;

I'd suggest you store all time/date information in UTC and convert when presenting the information to user. Whether you do this in MySQL or PHP depends on the application design.

like image 26
vhu Avatar answered Oct 13 '22 11:10

vhu