Reputation: 2843
I am trying to calculate time passed since a comment is posted. I found a function for this and it's working well
But I just noticed the time shown to user is wrong because of his/her timezone. I did some research and the solution seems to be passing the user's timezone offset to the php page using a javascript function called getTimezoneOffset
.
the problem is that I can't manage to use this Offset to make a timezone and use it on that function I linked above. With the help of another code is what I could gather so far :
function humanTiming ($time,$offset)
{
$isDST = 1; // Daylight Saving 1 - on, 0 - off
$timezoneName = timezone_name_from_abbr('', intval($offset, 10) * 36, $isDST);
$date = new DateTime($time, new DateTimeZone($timezoneName));
$time = strtotime($date);
$time = time() - $time; // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
And let's call the function like this :
echo humanTiming ($row['date'],"-240");
note : -240
is the value I get from running that javascript function, So it is probably my timezone offset.
First issue: It seems the value -240
is invalid and something like -0500
works.
Second issue: even If I try with the valid offset value, the function returns 42 years
Not sure how this 42 years is calculated but its totally wrong.
Upvotes: 1
Views: 2355
Reputation: 1972
You could offset everything like so:
$today=new DateTime("-$offset minutes");
$tomorrow=new DateTime("+1 day-$offset minutes");
Upvotes: 0
Reputation: 8415
A couple of problems:
The Javascript function getTimezoneOffset()
returns the timezone offset in minutes, however timezone_name_from_abbr()
expects the offset in seconds. So in your example of -240
that is actually -4
hours or -14396
seconds. You can fix your code by changing the math a little:
$timezoneName = timezone_name_from_abbr('', intval($offset) * 60, $isDST);
Since you've started using the DateTime
object, you can't then use strtotime
to get the Unix timestamp. Instead you need format()
:
$date = new DateTime($time, new DateTimeZone($timezoneName));
$time = $date->format('U');
This should get the result you are after. You were getting 42 years because the time was set to 0 (strtotime($date)
evaluated to false) which is Unix epoch - 1970.
Upvotes: 4