0v3k Shi3ld3r 0v3k Shi3ld3r - 4 months ago 17
MySQL Question

Time Function not correctly calculating

My time calculations are not correct I have a time.php that is called in my profile.php to calculate the last time a message was sent etc

I have the following line that calls the function time_passed for the row time

echo "time_passed"($row['time']);


Here is the CODE for calculating time

<?php

// DISPLAYS COMMENT POST TIME AS "1 year, 1 week ago" or "5 minutes, 7 seconds ago", etc...
function time_passed($timestamp){
//type cast, current time, difference in timestamps
$timestamp = (int) $timestamp;
$current_time = time();
$diff = $current_time - $timestamp;

//intervals in seconds
$intervals = array (
'year' => 31556926, 'month' => 2629744, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'minute'=> 60
);

//now we just find the difference
if ($diff == 0)
{
return 'just now';
}

if ($diff < 60)
{
return $diff == 1 ? $diff . ' second ago' : $diff . ' seconds ago';
}

if ($diff >= 60 && $diff < $intervals['hour'])
{
$diff = floor($diff/$intervals['minute']);
return $diff == 1 ? $diff . ' minute ago' : $diff . ' minutes ago';
}

if ($diff >= $intervals['hour'] && $diff < $intervals['day'])
{
$diff = floor($diff/$intervals['hour']);
return $diff == 1 ? $diff . ' hour ago' : $diff . ' hours ago';
}

if ($diff >= $intervals['day'] && $diff < $intervals['week'])
{
$diff = floor($diff/$intervals['day']);
return $diff == 1 ? $diff . ' day ago' : $diff . ' days ago';
}

if ($diff >= $intervals['week'] && $diff < $intervals['month'])
{
$diff = floor($diff/$intervals['week']);
return $diff == 1 ? $diff . ' week ago' : $diff . ' weeks ago';
}

if ($diff >= $intervals['month'] && $diff < $intervals['year'])
{
$diff = floor($diff/$intervals['month']);
return $diff == 1 ? $diff . ' month ago' : $diff . ' months ago';
}

if ($diff >= $intervals['year'])
{
$diff = floor($diff/$intervals['year']);
return $diff == 1 ? $diff . ' year ago' : $diff . ' years ago';
}
}

?>


The result is as follows

enter image description here

My table is

enter image description here

The time is inserted in the following format

enter image description here

The time gets inserted automatically when a query is ran, then I show back the results in a table above but its says 46 years ago , What is possible causing this ? Thanks

Answer

Just you need to do the following

change this line $timestamp = (int) $timestamp; to

$timestamp  = strtotime($timestamp);

and add the default time for your country. For example as I am from India I used to set date_default_timezone_set('Asia/Kolkata'); at the starting of function