I've noticed that Facebook, Twitter, and lots of other sites are using a relative date and time string description for user posts and comments.
For example, "comment written about 3 months ago" instead of "comment written on September 20, 2012." I decided to do the same thing on my site. In my site I need to display 1 day ago, 2 days ago, 3 days ago,...... 1 week ago, 2 weeks ago, .... 1 months ago, 2 months ago, ...... 1 year ago, 2 years ago... etc.
Already I have got user registered date and need to check it with current date and time and need to diplay it with above style on my home page.
In my database, user registered date format is like this .. '2012-09-23 09:11:02'
can anybody help me to build this script in php... and it will greatly appriciated.
Thank you.
Try the following code,
function time_elapsed_since ($postedDateTime){
$time = time() - $postedDateTime; // 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':'');
}
}
Usage:
time_elapsed_since($postedDateTime).' ago'; // 2012-09-23 09:11:02 format
Try with this
function time_ago($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] 'ago' ";
}
Im guessing they are using unixtime ie the number of seconds since 1970 (which is standard). I suggest that should also keep your dates in that format. If they are using unix time you can use the following date function in PHP to convert it to your format above:
<?php
date('Y-m-t H:i:s', $facebookTime);
Regards,
Kevin
Related
Actually I'd like to create a function which return me the date if the day is greater than one and it should return the time age like 1 hour ago.
I have done almost 80%, Time Ago functionality now I want to add one more feature.
function dateTimeExe ($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':'');
}
}
Please view output it may help to understand my question.
If day is less than 1 then it is working properly // 1 min ago or 1 hour ago
Now I want to add if day is greater than 1 then it should return date in this format // 18 May 2015.
What you can do is getting the timestamp from your datetime (http://php.net/manual/fr/class.datetime.php) thanks to getTimestamp() method and finally you can compare them with each other
Assuming $date is a Datetime instance :
$time = time() - $time->getTimestamp();
Actually, I add if statement in my function and now its working
if ($time>86400) {
return date('d F Y');
}else{
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'').' ago';
}
}
I found a function form SC to output human readable time. like `
5 hours, 1 hour, 5 years, etc
function human_time ($time)
{
$time = time() - strtotime($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 I have time as string: 2013-09-28 20:55:42
when I call this function human_time('2013-09-28 20:55:42')
then it return nothing, why ?
I have added strtotime in above function.
Please tell me what is wrong.
This is no ready-to-use code, but rather supposed to guide you the right way:
$then = new DateTime($time); // you might need to format $time using strtotime or other functions depending on the format provided
$now = new DateTime();
$diff = $then->diff($now, true);
echo $diff->format('Your style goes here');
See DateTime Manual for further documentation or feel free to ask here.
Edit: Link fixed.
Use example :
echo time_elapsed_string('2013-05-01 00:22:35');
echo time_elapsed_string('2013-05-01 00:22:35', true);
Output :
4 months ago
4 months, 2 weeks, 3 days, 1 hour, 49 minutes, 15 seconds ago
Link to the function.
ok i have a date
date('Y-m-d H:i:s');
how can we make it like 0 seconds ago or x year x month x day x minutes x seconds ago ? but without useing the str_time ( php 5.3.3 )
edit*
i mean is some.date - time.now = someyear some month someday someminutes someseconds ago.
like facebook or stackoverflow ( updated. i mean like that. – Adam Ramadhan 2 mins ago edit )
edit*
some say to use sktime ?
the 2 mins ago.
Thanks
Adam Ramadhan
You should try out this (looks exactly like the krike answer but this one is fixed!)
<?php
function ago($timestamp){
$difference = time() - $timestamp;
$periods = array("second", "minute", "hour", "day", "week", "month", "years", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
for($j = 0; $difference >= $lengths[$j]; $j++)
$difference /= $lengths[$j];
$difference = round($difference);
if($difference != 1) $periods[$j].= "s";
$text = "$difference $periods[$j] ago";
return $text;
}
?>
Just do this---
echo ago($timeofthethingyouwant);
And remember this works with this type of format of time----
time(); //Or it looks like this 1299951275!
This works for sure and it is great and light weight script! For more head to this link--
http://drupal.org/node/61565
Hope it works!
Why not just subtract 30 from the output of time() ?
date('Y-m-d H:i:s',time()-30);
time() returns the current time measured in terms of number of seconds since epoch, so subtracting 30 from it gives the timestamp of the time 30 sec ago
function nicetime($fromDate, $toDate = NULL, $precision = -1, $separator = ', ', $divisors = NULL) {
if ( is_null( $toDate ) ) {
$toDate = $this->date_get('Asia/Jakarta');
}
// Determine the difference between the largest and smallest date
$dates = array(strtotime($fromDate), strtotime($toDate));
$difference = max($dates) - min($dates);
// Return the formatted interval
return $this->format_interval($difference, $precision, $separator, $divisors);
}
/**
* Formats any number of seconds into a readable string
*
* #param int Seconds to format
* #param string Seperator to use between divisors
* #param int Number of divisors to return, ie (3) gives '1 Year, 3 Days, 9 Hours' whereas (2) gives '1 Year, 3 Days'
* #param array Set of Name => Seconds pairs to use as divisors, ie array('Year' => 31536000)
* #return string Formatted interval
*/
function format_interval($seconds, $precision = -1, $separator = ', ', $divisors = NULL)
{
// Default set of divisors to use
if(!isset($divisors)) {
$divisors = Array(
'Year' => 31536000,
'Month' => 2628000,
'Day' => 86400,
'Hour' => 3600,
'Minute' => 60,
'Second' => 1);
}
arsort($divisors);
// Iterate over each divisor
foreach($divisors as $name => $divisor)
{
// If there is at least 1 of thie divisor's time period
if($value = floor($seconds / $divisor)) {
// Add the formatted value - divisor pair to the output array.
// Omits the plural for a singular value.
if($value == 1)
$out[] = "$value $name";
else
$out[] = "$value {$name}s";
// Stop looping if we've hit the precision limit
if(--$precision == 0)
break;
}
// Strip this divisor from the total seconds
$seconds %= $divisor;
}
// FIX
if (!isset($out)) {
$out[] = "0" . $name;
}
var_dump($out);
// Join the value - divisor pairs with $separator between each element
return implode($separator, $out);
}
I found the following function when searching on google, i tested the code out and it seems to work perfectly.
function ago($timestamp){
$difference = time() - $timestamp;
$periods = array("second", "minute", "hour", "day", "week", "month", "years", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
for($j = 0; $difference >= $lengths[$j]; $j++)
$difference /= $lengths[$j];
$difference = round($difference);
if($difference != 1) $periods[$j].= "s";
$text = "$difference $periods[$j] ago";
return $text;
}
you would then call it as
echo ago($time);
Fairly simply - you need start and current timestamps. For instance, to see the number of minutes passed from a start date of this evening (8/22/2010 9pm PST):
$start = strtotime('8/22/2010 9pm');
printf('%d minutes ago', (time() - $start) / 60);
// My Output: 36 minutes ago. Will vary, depending on the current time/zone.
The 60 divisor is to get minutes. For seconds there'd be no division. For hours, days, years, etc. use different divisors. The following solution has a sample function for formatting timestamps:
How to display "12 minutes ago" etc in a PHP webpage?
I'm trying to work with dates for the first time, I did it something about that with Flash but it's different.
I have two different dates and I'd like to see the difference in hours and days with them, I've found too many examples but not what I'm loking for:
<?php
$now_date = strtotime (date ('Y-m-d H:i:s')); // the current date
$key_date = strtotime (date ("2009-11-21 14:08:42"));
print date ($now_date - $key_date);
// it returns an integer like 5813, 5814, 5815, etc... (I presume they are seconds)
?>
How can I convert it to hours or to days?
The DateTime diff function returns a DateInterval object. This object consists of variabeles related to the difference. You can query the days, hours, minutes, seconds just like in the example above.
Example:
<?php
$dateObject = new DateTime(); // No arguments means 'now'
$otherDateObject = new DateTime('2008-08-14 03:14:15');
$diffObject = $dateObject->diff($otherDateObject));
echo "Days of difference: ". $diffObject->days;
?>
See the manual about DateTime.
Sadly, it's a PHP 5.3> only feature.
Well, you can always use date_diff, but that is only for PHP 5.3.0+
The alternative would be math.
How can I convert it [seconds] to hours or to days?
There are 60 seconds per minute, which means there are 3600 seconds per hour.
$hours = $seconds/3600;
And, of course, if you need days ...
$days = $hours/24;
If you dont have PHP5.3 you could use this method from userland (taken from WebDeveloper.com)
function date_time_diff($start, $end, $date_only = true) // $start and $end as timestamps
{
if ($start < $end) {
list($end, $start) = array($start, $end);
}
$result = array('years' => 0, 'months' => 0, 'days' => 0);
if (!$date_only) {
$result = array_merge($result, array('hours' => 0, 'minutes' => 0, 'seconds' => 0));
}
foreach ($result as $period => $value) {
while (($start = strtotime('-1 ' . $period, $start)) >= $end) {
$result[$period]++;
}
$start = strtotime('+1 ' . $period, $start);
}
return $result;
}
$date_1 = strtotime('2005-07-31');
$date_2 = time();
$diff = date_time_diff($date_1, $date_2);
foreach ($diff as $key => $val) {
echo $val . ' ' . $key . ' ';
}
// Displays:
// 3 years 4 months 11 days
TheGrandWazoo mentioned a method for php 5.3>. For lower versions you can devide the number of seconds between the two dates with the number of seconds in a day to find the number of days.
For days, you do:
$days = floor(($now_date - $key_date) / (60 * 60 * 24))
If you want to know how many hours are still left, you can use the modulo operator (%)
$hours = floor((($now_date - $key_date) % * (60 * 60 * 24)) / 60 * 60)
<?php
$now_date = strtotime (date ('Y-m-d H:i:s')); // the current date
$key_date = strtotime (date ("2009-11-21 14:08:42"));
$diff = $now_date - $key_date;
$days = floor($diff/(60*60*24));
$hours = floor(($diff-($days*60*60*24))/(60*60));
print $days." ".$hours." difference";
?>
I prefer to use epoch/unix time deltas. Time represented in seconds and as such you can very quickly divide by 3600 for hours and divide by 24*3600=86400 for days.
I have a Date object ( from Pear) and want to subtract another Date object to get the time difference in seconds.
I have tried a few things but the first just gave me the difference in days, and the second would allow me to convert one fixed time to unix timestamp but not the Date object.
$now = new Date();
$tzone = new Date_TimeZone($timezone);
$now->convertTZ($tzone);
$start = strtotime($now);
$eob = strtotime("2009/07/02 17:00"); // Always today at 17:00
$timediff = $eob - $start;
** Note ** It will always be less than 24 hours difference.
Still gave somewhat wrong values but considering I have an old version of PEAR Date around, maybe it works for you or gives you an hint on how to fix :)
<pre>
<?php
require "Date.php";
$now = new Date();
$target = new Date("2009-07-02 15:00:00");
//Bring target to current timezone to compare. (From Hawaii to GMT)
$target->setTZByID("US/Hawaii");
$target->convertTZByID("America/Sao_Paulo");
$diff = new Date_Span($target,$now);
echo "Now (localtime): {$now->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo "Target (localtime): {$target->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo $diff->format("Diff: %g seconds => %C");
?>
</pre>
Are you sure that the conversion of Pear Date object -> string -> timestamp will work reliably? That is what is being done here:
$start = strtotime($now);
As an alternative you could get the timestamp like this according to the documentation
$start = $now->getTime();
To do it without pear, to find the seconds 'till 17:00 you can do:
$current_time = mktime ();
$target_time = strtotime (date ('Y-m-d'. ' 17:00:00'));
$timediff = $target_time - $current_time;
Not tested it, but it should do what you need.
I don't think you should be passing the entire Date object to strtotime. Use one of these instead;
$start = strtotime($now->getDate());
or
$start = $now->getTime();
Maybe some folks wanna have the time difference the facebook way. It tells you "one minute ago", or "2 days ago", etc... Here is my code:
function getTimeDifferenceToNowString($timeToCompare) {
// get current time
$currentTime = new Date();
$currentTimeInSeconds = strtotime($currentTime);
$timeToCompareInSeconds = strtotime($timeToCompare);
// get delta between $time and $currentTime
$delta = $currentTimeInSeconds - $timeToCompareInSeconds;
// if delta is more than 7 days print the date
if ($delta > 60 * 60 * 24 *7 ) {
return $timeToCompare;
}
// if delta is more than 24 hours print in days
else if ($delta > 60 * 60 *24) {
$days = $delta / (60*60 *24);
return $days . " days ago";
}
// if delta is more than 60 minutes, print in hours
else if ($delta > 60 * 60){
$hours = $delta / (60*60);
return $hours . " hours ago";
}
// if delta is more than 60 seconds print in minutes
else if ($delta > 60) {
$minutes = $delta / 60;
return $minutes . " minutes ago";
}
// actually for now: if it is less or equal to 60 seconds, just say it is a minute
return "one minute ago";
}