Nirmal Ram
Nirmal Ram

Reputation: 1732

PHP: Show time based on user's timezone

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 .

Upvotes: 8

Views: 10191

Answers (3)

Madan Sapkota
Madan Sapkota

Reputation: 26071

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.

Upvotes: 6

ElefantPhace
ElefantPhace

Reputation: 3814

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)

Upvotes: 1

Sam
Sam

Reputation: 2970

You must get the user information and set the default timezone

Look date_default_timezone_set()

And ip geolocation api

Upvotes: 3

Related Questions