Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Show time based on user's timezone

Tags:

timezone

php

I wonder if there is a way to get the timezone of the user in php and then display a time based on viewer's timezone. I know it can be done in javascript but i want a solution in php. I searched a lot but can't find a way to get this work.

So basically suppose the time is 8:30 GMT+0530. Its in indian timezone i want if a user views this in Ne York then it should be 21:30 .

like image 846
Nirmal Ram Avatar asked Mar 01 '13 01:03

Nirmal Ram


3 Answers

If you added the users Timezone while registering or you know users Timezone somehow, then you can try this...

$users = [
    [
        'username' => 'foo',
        'timezone' => 'America/Los_Angeles'
    ],
    [
        'username' => 'bar',
        'timezone' => 'America/New_York'
    ]
];

foreach ($users as $user) {
    date_default_timezone_set($user['timezone']);
    echo $user['username'] . ' date and time is ' . date('Y-m-d H:i:s') . '<br />';
}

Output

foo time is 2013-02-28 18:13:49
bar time is 2013-02-28 21:13:49

You can also user Timezone in JavaScrpt Getting the client's timezone in JavaScript. Make an Ajax request and Save in PHP Session or database.

like image 72
Madan Sapkota Avatar answered Nov 02 '22 09:11

Madan Sapkota


You must get the user information and set the default timezone

Look date_default_timezone_set()

And ip geolocation api

like image 3
Sam Avatar answered Nov 02 '22 10:11

Sam


You can get the users timezone by crossing their IP with many available geolocation databases, such as IPInfoDB

http://ipinfodb.com/ip_location_api.php

you will need to register for a free API key, but they also provide you with a working example(above)

like image 1
ElefantPhace Avatar answered Nov 02 '22 09:11

ElefantPhace