I know this question has been asked several times and I found so many tutorials, blog posts about converting timestamp to ago time in php..
I have tried countless codes and nothing seems to work for me...
I either get a blank page with no errors (i have error rerposting on my php page), or I get some strange numbers in my page..
so I thought someone here could shed a light on this for me..
Basically I am saving date like so:
$date = date('Y-m-d H:i:s');
I simply save it in mysql database...
and I echo it like so:
echo $date;
so now what I need to know is how I can convert the echo $date; to something like 1 minutes ago, 10 minutes ago, 1 hour ago etc etc every time the page closes and reopens?
I did try so many functions that I found on google and noon seem to do anything!
could someone please advise on this issue?
Thanks
EDIT:
I used this code as stated in the answer but I still get the $date echo-ed exactly the same way as its stored in the database which is this format: 2014-10-06 22:54:54
$date = date('Y-m-d H:i:s');
$time1 = new DateTime($date);
$now = new DateTime();
$interval = $time1->diff($now);
if ($interval->y) $date = $interval->y . ' years';
elseif ($interval->m) $date = $interval->m . ' months';
elseif ($interval->d) $date = $interval->d . ' days';
elseif ($interval->h) $date = $interval->h . ' hours';
elseif ($interval->i) $date = $interval->i . ' minutes';
echo $date;
You should use the DateTime class to get the difference between 2 times, ie;
$time1 = new DateTime('2014-10-06 09:00:59');
$now = new DateTime();
$interval = $time1->diff($now,true);
and then use that difference (which is a DateInterval object, $interval) to find the smallest time difference like this;
if ($interval->y) echo $interval->y . ' years';
elseif ($interval->m) echo $interval->m . ' months';
elseif ($interval->d) echo $interval->d . ' days';
elseif ($interval->h) echo $interval->h . ' hours';
elseif ($interval->i) echo $interval->i . ' minutes';
else echo "less than 1 minute";
which should echo (at time of writing) 13 hours.
Hope this helps.
Check this function intval() - http://php.net/manual/en/function.intval.php
The following code should help you out
$seconds_ago = (time() - strtotime('2014-01-06 15:25:08'));
if ($seconds_ago >= 31536000) {
echo "Seen " . intval($seconds_ago / 31536000) . " years ago";
} elseif ($seconds_ago >= 2419200) {
echo "Seen " . intval($seconds_ago / 2419200) . " months ago";
} elseif ($seconds_ago >= 86400) {
echo "Seen " . intval($seconds_ago / 86400) . " days ago";
} elseif ($seconds_ago >= 3600) {
echo "Seen " . intval($seconds_ago / 3600) . " hours ago";
} elseif ($seconds_ago >= 60) {
echo "Seen " . intval($seconds_ago / 60) . " minutes ago";
} else {
echo "Seen less than a minute ago";
}
Related
I've been struggling with this issue for a few days now, so I'm looking for any insights you may have. I have been using the following to input a timestamp on user posts:
//Timeframe
$date_time_now = date("Y-m-d H:i:s");
$start_date = new DateTime($date_time); //Time of post
$end_date = new DateTime($date_time_now); //Current time
$interval = $start_date->diff($end_date); //Difference between dates
if($interval->y >= 1) {
if($interval == 1)
$time_message = $interval->y . " year ago"; //1 year ago
else
$time_message = $interval->y . " years ago"; //1+ year ago
}
else if ($interval-> m >= 1) {
if($interval->d == 0) {
$days = " ago";
}
else if($interval->d == 1) {
$days = $interval->d . " day ago";
}
else {
$days = $interval->d . " days ago";
}
if($interval->m == 1) {
$time_message = $interval->m . " month " . $days;
}
else {
$time_message = $interval->m . " months " . $days;
}
}
else if($interval->d >= 1) {
if($interval->d == 1) {
$time_message = "Yesterday";
}
else {
$time_message = $interval->d . " days ago";
}
}
else if($interval->h >= 1) {
if($interval->h == 1) {
$time_message = $interval->h . " hour ago";
}
else {
$time_message = $interval->h . " hours ago";
}
}
else if($interval->i >= 1) {
if($interval->i == 1) {
$time_message = $interval->i . " minute ago";
}
else {
$time_message = $interval->i . " minutes ago";
}
}
else {
if($interval->s < 30) {
$time_message = "Just now";
}
else {
$time_message = $interval->s . " seconds ago";
}
}
In the html I have it outputting as:
<span class='comment-date'>$time_message</span>
Everything was working fine until recently, I didn't notice until a few days ago but I suspect it began when the year changed to 2019. What's happening is on some of the posts I'm getting the following error:
Notice: Object of class DateInterval could not be converted to int in C:\xampp\htdocs\LEARN_123\includes\classes\Post.php on line 311
Line 311 refers to if($interval == 1) in the above code. I'm also noticing that for posts that are over 1 year old, it's not deferring to the else statement $time_message = $interval->y . " years ago"; //1+ year ago. For some it just says 1 year ago, others I'm getting the Notice:
I've been going through this but can't seem to figure it out. Can anyone see what might be happening, or have any leads on how I can correct this?
if($interval == 1) should be if($interval->y == 1)
Also every where you ask if($interval->y|m|d|h|i|s==1
you don't need the $time_message = $interval->y|m|d|h|i|s . " frame ago";
it could more simply be $time_message = "1 frame ago";
where frame = year, month, day, hour, minute, second
or you could simplify more and get rid of the extra if/else statements with something like the following:
$time_message = $interval->y|m|d|h|i|s . " frame" . ($interval->y|m|d|h|i|s > 1 ? "s " : " ") . ago";
Just to close out the question & keep things tidy, I thought I would post the answer here. As pointed out in the comments, I'm receiving the Notice: on these b/c my conditional if($interval == 1) is not able to be converted since variable $interval is defined as a DateInterval object. The syntax was corrected to if($interval->y == 1) & this now functions as expected.
I'm trying to appreciate the avalanche that the small things can create, but sometimes it's just a pain in the a$$ too.
I am trying to get difference between dates using this code, but it can not produce the right result, what is wrong with this code, I could not find out.
$birth_date = new DateTime("1977-03-23");
$current_date = new DateTime();
$diff = $birth_date->diff($current_date);
echo $years = $diff->y . " years " . $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $months = ($diff->y * 12) + $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $weeks = floor($diff->days/7) . " weeks " . $diff->d%7 . " day(s)"; echo "<br/>";
echo $days = $diff->days . " days"; echo "<br/>";
It shows Outout as - 39 years 10 months 16 days
But I think the output should be - 39 years 10 months 7 days
It calculate year and month correctly but days are wrong.
maybe this function can help you:
function leap_year($date1, $date2)
{
$y1 = $date1->format('Y');
if ($date1->format('m')>2) $y1++;
$y2 = $date2->format('Y');
if ($date2->format('m')<=2) $y2--;
$leap_years = 0;
for($i = $y1; $i <= $y2; $i++)
{
//echo date("Y", strtotime($i . '-01-01')).' '.date("L", strtotime($i . '-01-01')).'<br/>';
if (date("L", strtotime($i . '-01-01')) == 1)
$leap_years++;
}
return $leap_years;
}
echo leap_year($birth_date, $current_date);
Maybe you missed the leap years, this could explain the difference of 9 days, e.g.
9 * 4 y = 36 years
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to show last seen in user's profile in my php page. I am storing user's logout time in database as 2014-01-06 15:25:08 (store in $last_log) with DATETIME datatype. Now i want to display last seen x mins ago. And it's auto update in x day ago, x month ago.
I want same as here when we add comment & its time ".......ago" updates.
How can i display this.
// intval() - http://php.net/manual/en/function.intval.php
$seconds_ago = (time() - strtotime('2014-01-06 15:25:08'));
if ($seconds_ago >= 31536000) {
echo "Seen " . intval($seconds_ago / 31536000) . " years ago";
} elseif ($seconds_ago >= 2419200) {
echo "Seen " . intval($seconds_ago / 2419200) . " months ago";
} elseif ($seconds_ago >= 86400) {
echo "Seen " . intval($seconds_ago / 86400) . " days ago";
} elseif ($seconds_ago >= 3600) {
echo "Seen " . intval($seconds_ago / 3600) . " hours ago";
} elseif ($seconds_ago >= 60) {
echo "Seen " . intval($seconds_ago / 60) . " minutes ago";
} else {
echo "Seen less than a minute ago";
}
Try this function
function get_timeago( $ptime )
{
$etime = time() - $ptime;
if( $etime < 1 )
{
return 'less than '.$etime.' second ago';
}
$a = array( 12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach( $a as $secs => $str )
{
$d = $etime / $secs;
if( $d >= 1 )
{
$r = round( $d );
return 'about ' . $r . ' ' . $str . ( $r > 1 ? 's' : '' ) . ' ago';
}
}
}
Usage :
$timestamp = strtotime("2014-11-14 17:15:59");
echo get_timeago( $timestamp );
try something like this:
$datetime1 = new DateTime('2014-01-06 15:25:08');
$datetime2 = new DateTime();
$interval = $datetime1->diff($datetime2);
echo $interval->format('%a days')."<br>";
echo $interval->m." Months";
for more read this:http://php.net/manual/en/datetime.diff.php
try this
$date1 = strtotime('2014-12-06 15:25:08');
$date2 = strtotime(date('Y-m-d H:i:s'));
$seconds_diff = $date2 - $date1;
echo round(abs($seconds_diff) / 60,2). " mins ago";
Use the date_diff function.
See http://php.net/manual/en/function.date-diff.php
"Powerful Function to get two date difference."
In short:
// $datetime1 and $datetime2 are UNIX timestamps.
$interval = date_diff($datetime1, $datetime2);
echo $interval->format($differenceFormat);
I'm creating a countdown for how long people can do specific functions on a specific page. I've made a countdown, but he is going under 0, so he's counting further negatively.
I'm printing out the countdown like this:
-4 days -10 h -3 m -34 s remaining to run 1210 meter
My countdown,
$Date = "" . $groups['group_date'] . "";
$stopDate = date('Y-m-d H:i:s', strtotime($Date. ' +' . $periodOfRunning . 'days'));
<h3><?php $rem = strtotime($stopDate) - time();
$day = floor($rem / 86400);
$hr = floor(($rem % 86400) / 3600);
$min = floor(($rem % 3600) / 60);
$sec = ($rem % 60);
if($day) echo "$day days ";
if($hr) echo "$hr h ";
if($min) echo "$min m ";
if($sec) echo "$sec s";
echo " remaining to run " . $totalDistanceToDo . " meter";
?></h3>
If you use DateTime() you can compare the two times and see if the stop time is in the past. If it is, display a different message. Also, this makes getting the interval between the two easier to get and display:
$now = new DateTime();
$stopdate = new DateTime($stopDate);
if ($stopdate > $now) {
$diff = $now->diff($stopTime);
echo $diff->format('%d days, %h hours, %i minutes, %s seconds');
echo " remaining to run " . $totalDistanceToDo . " meter";
}
else {
// negative time. display something else
}
Keep in mind if you don't want to display zero values for time units it will be a little more complex:
$now = new DateTime();
$stopdate = new DateTime($stopDate);
if ($stopdate > $now) {
$diff = $now->diff($stopTime);
if ($diff->d > 0) echo $diff->d . ' days, ';
if ($diff->h > 0) echo $diff->h . ' hours, ';
if ($diff->i > 0) echo $diff->i . ' minutes, ';
if ($diff->s > 0) echo $diff->s . ' seconds';
echo " remaining to run " . $totalDistanceToDo . " meter";
}
else {
// negative time. display something else
}
I have used many functions for relative time in php but that give different results...help me
My functions :
<?php
function pretty_relative_time($time) {
if ($time !== intval($time)) { $time = strtotime($time); }
$d = time() - $time;
if ($time < strtotime(date('Y-m-d 00:00:00')) - 60*60*24*3) {
$format = 'F j';
if (date('Y') !== date('Y', $time)) {
$format .= ", Y";
}
return date($format, $time);
}
if ($d >= 60*60*24) {
$day = 'Yesterday';
if (date('l', time() - 60*60*24) !== date('l', $time)) { $day = date('l', $time); }
return $day . " at " . date('g:ia', $time);
}
if ($d >= 60*60*2) { return intval($d / (60*60)) . " hours ago"; }
if ($d >= 60*60) { return "about an hour ago"; }
if ($d >= 60*2) { return intval($d / 60) . " minutes ago"; }
if ($d >= 60) { return "about a minute ago"; }
if ($d >= 2) { return intval($d) . " seconds ago"; }
else {return "Just Now"; }
}
function plural($num) {
if ($num != 1)
return "s";
}
function getRelativeTime($date) {
$diff = time() - strtotime($date);
if ($diff<60)
return $diff . " second" . plural($diff) . " ago";
$diff = round($diff/60);
if ($diff<60)
return $diff . " minute" . plural($diff) . " ago";
$diff = round($diff/60);
if ($diff<24)
return $diff . " hour" . plural($diff) . " ago";
$diff = round($diff/24);
if ($diff<7)
return $diff . " day" . plural($diff) . " ago";
$diff = round($diff/7);
if ($diff<4)
return $diff . " week" . plural($diff) . " ago";
return "on " . date("F j, Y", strtotime($date));
}
echo pretty_relative_time('2012-08-06 8:04:15') ;echo "<br/>";
echo getRelativeTime('2012-08-06 8:04:15');
?>
OutPut :
Just Now // for first function
-15747 seconds ago // for second function
any settings in db ?.....i have used DATETIME for date...
You haven't made clear what output you're expecting, but from your later comment it should be "1 hour ago"? In which case I suspect you are suffering from timezone problems - most likely the dreaded "Daylight Savings Time". Try echoing date('Y-m-d H:i:s') in PHP and seeing if it comes out with the value you expect.
The discrepancy could be in the timezone set in php.ini, or the system clock of the webserver itself, not matching the timezone setting of the database, or the system clock on that server.