PHP: Show time based on user's timezone

2019-04-06 13:49发布

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 .

标签: php timezone
3条回答
Lonely孤独者°
2楼-- · 2019-04-06 14:13

You must get the user information and set the default timezone

Look date_default_timezone_set()

And ip geolocation api

查看更多
一纸荒年 Trace。
3楼-- · 2019-04-06 14:29

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.

查看更多
放我归山
4楼-- · 2019-04-06 14:32

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)

查看更多
登录 后发表回答