sm21guy
sm21guy

Reputation: 626

time() with different timezones

How can i get user's local time using php time() or there is another way to do it? Which means it will be in their timezone.

I need to calculate time ago with user's local time, here's a nice script i found for the time ago function:

<?php
function timeago($time)  
    {  
    $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");  
    $lengths = array("60","60","24","7","4.35","12","10");  

    $now = time();

    $difference     = $now - $time;  
    $tense         = "ago";  

    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++)   
        {  
        $difference /= $lengths[$j];  
        }  

    $difference = round($difference);  

    if($difference != 1)   
        {  
        $periods[$j].= "s";  
        }  

    return "$difference $periods[$j] $tense";  
    }  
?>

<?php

$date = strtotime('2012-04-15 07:41:03');
$datep = timeago($date);

echo $datep;
?>

from the above script , i use the time() but it only gets my server time not the local time at my side. how can i get my local time(user's local time)?

Upvotes: 1

Views: 281

Answers (3)

Aram Gevorgyan
Aram Gevorgyan

Reputation: 511

There's not a server-based/PHP method for getting local time. You have to get it from the client via Javascript. Google "bitbucket timezone detect" and use it to set a "local_timezone" cookie that you can read from PHP and set via date_default_timezone_set()

Upvotes: 0

RichieAHB
RichieAHB

Reputation: 2088

I'm not sure it's always possible to get local time from the sever without the client passing you information - javascript being a good example. The way I do it (not my idea, read it somewhere) is to set a local time cookie with javascript and get PHP to read the cookie and then use that data with date_default_timezone_set(). I think that's the only bulletproof answer and it works fine for me.

EDIT: I read it from http://php.net/manual/en/function.localtime.php

Upvotes: 1

TJHeuvel
TJHeuvel

Reputation: 12618

Best way to do this would be client-side. Use Javascript's Date functions, and send them to PHP.

Upvotes: 0

Related Questions