I am using codeigniter and I have this code below It converts date in to a elapsed time to something like Asked 1 month, 3 weeks ago
If the date is older than a month I would like it to only display like date Asked Sept 01 05:34:13 and if older than a year Asked Sept 01 2015 05:34:13
Currently if time is under month prints out like below which is fine
example Asked 1 minute, 14 seconds ago
example Asked 2 weeks, 3 hours ago
$this->when_was_question_posted(strtotime('2016-09-01 05:34:13'))
Question how can I make sure that if the date is older than a month
then display like date Asked Sept 01 05:34:13 and if older than a
year Asked Sept 01 2015 05:34:13
function when_was_question_posted($distant_timestamp, $max_units = 2) {
$i = 0;
$time = time() - $distant_timestamp; // to get the time since that moment
$tokens = [
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
];
$responses = [];
while ($i < $max_units) {
foreach ($tokens as $unit => $text) {
if ($time < $unit) {
continue;
}
$i++;
$numberOfUnits = floor($time / $unit);
$responses[] = $numberOfUnits . ' ' . $text . (($numberOfUnits > 1) ? 's' : '');
$time -= ($unit * $numberOfUnits);
break;
}
}
if (!empty($responses)) {
return 'Asked ' . implode(', ', $responses) . ' ago';
}
return 'Just now';
}
Here is something to get you going...
$date_now = new DateTime();
$date = new DateTime('2014-04-01 00:00:00');
$interval = $date_now->diff($date);
if($interval->y > 0) {
echo "More than a year";
echo "<br>";
$display_date = $date->format('M d Y h:i:s');
} elseif($interval->m > 0) {
echo "More than a month";
echo "<br>";
$display_date = $date->format('M d h:i:s');
} else {
// Call your existing function
}
Related
I would like to post the actual date of an article (i.e. April 5, 2015) if it has been a year or more since its post. If less than a year, I would like to use the time ago function (i.e. 6 months ago).
I've tried commenting out the year in the HumanTiming Time Ago Function (posted by arnorhs) and adding an if/else condition to it
$time = strtotime('2015-04-05 17:25:43');
echo 'event happened '.humanTiming($time).' ago';
function humanTiming ($time)
{
$time = time() - $time; // to get the time since that moment
$time = ($time<1)? 1 : $time;
$tokens = array (
//31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
if($time > $tokens){
echo "April 5, 2015";
} else {
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
}
I expect the output to be "April 5, 2015", but it ignores the if/else condition and posts the date as "36 months ago".
How can I achieve the result I'm looking for?
using DateTime is way simpler
$now = new DateTime();
$then = new DateTime('April 5, 2015');
$diff = $now->diff($then); // returns DateInterval object or false on failure
if ($diff->y >= 1) {
// show your date
echo $then->format('Y-m-d H:i:s');
} else {
// show the interval
echo $diff->format('%d days ago');
}
check the documentation for more info
https://www.php.net/manual/en/class.dateinterval.php
https://www.php.net/manual/en/dateinterval.format.php
You need to check against the time of one year ago - not against the array $tokens. You can get the time of one year ago from strtotime('1 year ago'). If that is lesser than time()-$time (the current timestamp minus the $time timestamp), then the input-time is more than one year ago.
function humanTiming ($time) {
$time = time() - $time; // to get the time since that moment
$time = ($time<1)? 1 : $time;
$tokens = array (
//31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
if (time()-$time < strtotime("1 year ago")) {
return date("F jS, Y", time()-$time);
} else {
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'').' ago';
}
}
}
echo 'event happened '.humanTiming($time).'';
Live demo at https://3v4l.org/UH9df
<?php
$time = strtotime('2014-01-01 17:25:43');
function humanTiming ($time)
{
$back_time = $time;
$time = time() - $time; // to get the time since that moment
$time = ($time<1)? 1 : $time;
$tokens = array (
//31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < 31536000){
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
return date("Y-m-d H:i:s", $back_time);
}
echo 'event happened '.humanTiming($time);
?>
Everyone's different. I personally like to convert dates into unix timestamps (actual whole numbers) and work from there. Between the function and the function call are some display lines (echos) I added to give you a visual of what's happening. You can remove them, obviously.
<?php
//first here's the function
function date_less_year($entered_date_unix)
{
$difference = time() - $entered_date_unix;
//31536000 is a 'unix year'
if ($difference <= 31536000)
{
return true; //is less than or equal to a year
}
else if ($difference > 31536000)
{
return false; //is more than a year
}
}
/* display in the format you asked for. you can google 'php date' to learn of
* different formats you can use
*/
$entered_date_string = '2015-04-05 17:25:43';
$entered_date_to_display = date($entered_date_string);
echo $entered_date_to_display . ' is the date entered<br/>';
//let's turn to a unix timestampe to compare differences
$entered_date_unix = strtotime($entered_date_string);
echo $entered_date_unix . ' is the unix timestamp for entered date<br/>';
echo time() . ' is unix time for NOW <br/>';
if (date_less_year($entered_date_unix) == true)
{
//do something for less than a year
echo 'is less than a year!';
}
else
{
//do something for more than a year
echo 'is more than a year!';
}
?>
Here is how the time shows in the database right now:
2016-05-07 21:18:21
Right now, this is how it does to convert it:
function time_elapsed_string($datetime) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
$string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
when I do this it converts everything. BUT i want it to only show however many seconds, however many minutes, however many hours and if it's 24 hours, then it's 1 day, and 1 day. everything else I want it to show in this format: F j, Y g:ia
/**
* Format a unix timestamp in a 'time ago' format,
* e.g. 15 minutes ago or 7 days ago.
*
* #param integer $time
* #return string
*/
function ago($time)
{
$config = array(
array('second', 'seconds'),
array('minute', 'minutes'),
array('hour', 'hours'),
array('day', 'days'),
array('week', 'weeks'),
array('month', 'months'),
array('year', 'years'),
array('decade', 'decades'),
);
list($periods, $lengths, $now) = array($config, [60, 60, 24, 7, 4.35, 12, 10], time());
$difference = $now - $time;
for ($j = 0; $difference >= $lengths[$j] and $j < count($lengths) - 1; $j++)
{
$difference /= $lengths[$j];
}
$difference = round($difference);
$period = $difference == 1 ? $periods[$j][0] : $periods[$j][1];
if ($difference == 0)
{
return 'Just now';
}
return "${difference} ${period} ago";
}
$old_date = "2016-05-07 21:18:21";
$date311 = date('d-m-Y H:i:s', strtotime($old_date));
$date31 = date_create($date311);
//creating a date object
date_default_timezone_set("Asia/Calcutta");
$date411 = date('d-m-Y H:i:s');
$date41 = date_create($date411);
//calculating the difference between dates
//the dates must be provided to the function as date objects that's why we were setting them
//as date objects and not just as strings
//date_diff returns an date object wich can be accessed as seen below
$diff341 = date_diff($date41, $date31);
//accesing days
$days1 = $diff341->d;
//accesing months
$months1 = $diff341->m;
//accesing years
$years1 = $diff341->y;
//accesing hours
$hours1=$diff341->h;
//accesing minutes
$minutes1=$diff341->i;
//accesing seconds
$seconds1=$diff341->s;
echo '<center>';
echo '<br /><div style="background-color:green;color:#fff;padding:10px;width:600px;font-size:16px">
<b>The difference between '.$date311.' and '.$date411.'
<br />is: ' . $years1 . ' year(s), ' . $months1 . ' month(s), '. $days1 . ' day(s), '.$hours1.' hour(s),
'.$minutes1.' minute(s), '.$seconds1.' second(s) </b>
</div><br />';
echo '</center>';
Result :-
Good day guys, I am having a bit trouble of how can I make this like xx month/s ago and year/s ago if the days reach the number of months/years. Is it possible ? Anyway I'm making a messaging module. This is my code. Advance thank you for your help guys
<?php
date_default_timezone_set('Asia/Manila');
$now = strtotime(date("Y-m-d H:i:s"));
$date = strtotime($key->message_date); //this is the date where message was sent
$dateDiff = abs($now - $date);
$fullDays = floor($dateDiff/(60*60*24));
if($fullDays==0)
{
echo " Today ";
}
else if($fullDays==1)
{
echo " Yesterday ";
}
else
{
echo $fullDays ." days ago";
}
$at=date('g:iA',$date)
?> at <?php echo $at?>
You can use this function you have Pass message time as an argument
function convert_time($ptime){
$etime = time() - $ptime;
if($etime < 1){
return '0 seconds';
}
$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 $r . ' ' . $str . ($r > 1 ? 's' : '') . ' ago';
}
}
}
In this function you can get "(1) second/minute/hour/day/month/year ago"
This question already has answers here:
Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...
(32 answers)
Closed 8 years ago.
I am using the following php function to convert my standard DATETIME result into a facebook style time ago, which shows the number of seconds, minutes and hours, days etc of that date.
Here's my php function:
<?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"; }
return "a few seconds ago";
}
?>
And here's where I call the function:
echo pretty_relative_time($row1['date']);
the problem I'm having is the script almost works 100%, however if something is dated within an hour it only ever shows 'about an hour ago' even if I've posted something within a couple of minutes or seconds. Can someone please show me what I am doing wrong? My date is stored as a DATETIME stamp
You can use this function its working 100% correct. . .
function Myfunction ($time)
{
$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 call in this way. .
$time = strtotime($time);
$time = Myfunction($time);
I have a timestamp and would like to show my users... last sent 1 day, 23 hours, 54 minutes, and 33 seconds ago. I know how to get the difference in time...
$timePast = '2012-08-18 22:11:33';
$timeNow = date('Y-m-d H:i:s');
// gives total seconds difference
$timeDiff = strtotime($timeNow) - strtotime($timePast);
Now I am stuck not being able to show the time like above.
x day, x hours, x mins, x seconds where all the x's should add up to the total seconds time difference. I know the following...
$lastSent['h'] = round($timeDiff / 3600);
$lastSent['m'] = round($timeDiff / 60);
$lastSent['s'] = $timeDiff;
Need you help! Thanks in advance.
After this:
$timeDiff = strtotime($timeNow) - strtotime($timePast);
add:
if ($timeDiff > (60*60*24)) {$timeDiff = floor($timeDiff/60/60/24) . ' days ago';}
else if ($timeDiff > (60*60)) {$timeDiff = floor($timeDiff/60/60) . ' hours ago';}
else if ($timeDiff > 60) {$timeDiff = floor($timeDiff/60) . ' minutes ago';}
else if ($timeDiff > 0) {$timeDiff .= ' seconds ago';}
echo $timeDiff;
Don't do date math manually!
PHP can work out all of the date/time math for you, using the DateTime and DateInterval classes.
Getting an interval between two dates
$timePast = new DateTime('2012-08-18 22:11:33');
$timeNow = new DateTime;
$lastSent = $timePast->diff($timeNow);
// $lastSent is a DateInterval with properties for the years, months, etc.
Formatting example
A function for getting a formatted string might look like the following (though this is only one super-basic way, of many).
function format_interval(DateInterval $interval) {
$units = array('y' => 'years', 'm' => 'months', 'd' => 'days',
'h' => 'hours', 'i' => 'minutes', 's' => 'seconds');
$parts = array();
foreach ($units as $part => $label) {
if ($interval->$part > 0) {
$parts[] = $interval->$part . ' ' . $units[$part];
}
}
return implode(', ', $parts);
}
echo format_interval($lastSent); // e.g. 2 days, 24 minutes, 46 seconds
I took Kalpesh's code and made it work by using floor instead of round and by calculating the different frictions of the day. Here it goes:
function timeAgo ($oldTime, $newTime) {
$timeCalc = strtotime($newTime) - strtotime($oldTime);
$ans = "";
if ($timeCalc > 60*60*24) {
$days = floor($timeCalc/60/60/24);
$ans .= "$days days";
$timeCalc = $timeCalc - ($days * (60*60*24));
}
if ($timeCalc > 60*60) {
$hours = floor($timeCalc/60/60);
$ans .= ", $hours hours";
$timeCalc = $timeCalc - ($hours * (60*60));
}
if ($timeCalc > 60) {
$minutes = floor($timeCalc/60);
$ans .= ", $minutes minutes";
$timeCalc = $timeCalc - ($minutes * 60);
}
if ($timeCalc > 0) {
$ans .= "and $timeCalc seconds";
}
return $ans . " ago";
}
$timePast = '2012-08-18 22:11:33';
$timeNow = date('Y-m-d H:i:s');
$t = timeAgo($timePast, $timeNow);
echo $t;
Output:
1 days, 16 hours, 11 minutes and 18 seconds ago
You'll need a lot of if's, the modulus (%), floor() (not round())
Or Google ;-)