Convert 2010-04-16 16:30:00 to "Tomorrow Afternoon" or convert another date to "this afternoon", "next year", "next week wednesday". You get the picture.
Anyone know of a PHP or Javascript library that can do this?
I think you can come a long way with what is said here: Calculate relative time in C#
The logic is there, and it's not too hard to do the javascript equivalent if a solution in a different language suits you.
There might be more elegant solutions out there (look for Natural language formatting), but personally I couldn't find any.
I would suggest calculating the distance from now to the date you're formatting, and using thresholds.
Pseudo solution:
diff = now - date
if (diff < one_day)
format for today
if (diff < two_days)
format for tomorrow
if (diff < one_week)
format using days from now
.
.
.
The comparison will work for both past and future dates, as long as you use compare with the abs value of diff. Display timeunit ago or timeunit from now by checking if diff is positive or negative.
For the morning, afternoon, evening etc. you only need to check for the time of day in the date, and regarding the formatting type you hit, either display the time as numbers (far away), or natural language (recent or near date).
function gett($sam){
$times = time() - $sam;
if ($times == 60){
$times = "a minute ago";
}
if (($times != 1) && ($times < 60) && ($times != 0)){
$times = "$times seconds ago";
}
if ($times == 0){
$times = "less than a second ago";
}
if ($times == 1){
$times = "a second ago";
}
if ($times > 60 && $times < 3600){
$times = ceil($times/60)." minutes ago";
}
if($times == 3600){
$times = "an hour ago";
}
if($times > 3600 && $times < 86400){
$times = ceil($times/3600)." hours ago";
}
if($times == 86400){
$times = "a day ago";
}
if($times > 86400){
$times = ceil($times/86400)." days ago";
}
return $times; }
Usage:
$updated = gett($timestamp);
where $timestamp is pretty self-explanatory..
From this link -> How do I calculate relative time in C#?
function posted(t) {
var now = new Date();
var diff = parseInt((now.getTime() - Date.parse(t)) / 1000);
if (diff < 60) { return 'less than a minute ago'; }
else if (diff < 120) { return 'about a minute ago'; }
else if (diff < (2700)) { return (parseInt(diff / 60)).toString() + ' minutes ago'; }
else if (diff < (5400)) { return 'about an hour ago'; }
else if (diff < (86400)) { return 'about ' + (parseInt(diff / 3600)).toString() + ' hours ago'; }
else if (diff < (172800)) { return '1 day ago'; }
else {return (parseInt(diff / 86400)).toString() + ' days ago'; }
}
Related
Here is a PHP function I have designed, which is supposed to determine the amount of time passed in secs,mins,hours,days,weeks,months, and years - depending upon which bracket it is beneath. However Ive noticed that the values being returned seem to increase faster than actual time (within 30 mins, it outputs "1 weeks ago"). Im wondering if $time is actually in millis? That said, for the first 2 mins it outputs relatively accurate results.
Note: Running on 1and1 host.
Here's the function:
function get_relative_date($conn,$date,$post_id){
#get current timestamp
$q = "SELECT NOW() - INTERVAL 1 HOUR - `timestamp` FROM `posts` WHERE id=".$post_id.";";
# - INTERVAL 1 HOUR added due to server running 1 hour ahead.
$result = mysqli_query($conn,$q);
if ($result != null && $result != false){
$row = mysqli_fetch_array($result,MYSQLI_BOTH);
$time = $row[0]; #time passed since post
$min = 60;
$hour = $min*60;
$day = $hour*24;
$week = $day*7;
$month = $week*4;
$year = $month*12;
if ($time < $min){
return $time." secs ago";
}
if ($time < $hour){
return round(($time / $min))." mins ago";
}
if ($time < $day){
return round(($time / $hour))." hours ago";
}
if ($time < $week){
return round(($time / $day))." days ago";
}
if ($time < $month){
return round(($time / $week))." weeks ago";
}
if ($time < $year){
return round(($time / $month))." months ago";
}
if ($time >= $year){
return round(($time / $year))." years ago.";
}
return false;
}
}
Cheers.
I tried your query out and instead of 2 minutes and 40 seconds (in seconds) I was receiving 240 and instead of 1 hour 3 minutes and 40 seconds (in seconds) I got 10340.
You need this:
SELECT TIME_TO_SEC(TIMEDIFF(NOW(),`timestamp`)) FROM `posts` ...
This will select the time difference in seconds and hopefully give you the desired result.
I spent some time doing this quick little function (I didn't use the default one because I wanted a bit more customization later on). I made a post that has $checkTime = '0';, and when run through this function it comes back as 49 years ago.
Why is it returning that when January 1970 was only 45 years ago? Are the extra 4 years coming from time differences and leap years?
The other times seem to work correct (recent ones), but the ones I set to 0 say that and I'm just curious where the bug is, or what I might be overlooking.
function relativeTime($string) {
$currentTime = time();
$checkTime = $string;
$timeDifference = $currentTime - $checkTime;
if($timeDifference > '0') {
$timeSeconds = round(($timeDifference / 60) * 60);
$timeMinutes = round($timeSeconds / 60);
$timeHours = round($timeMinutes / 60);
$timeDays = round($timeHours / 24);
$timeWeeks = round($timeDays / 7);
$timeMonths = round($timeWeeks / 4);
$timeYears = round($timeMonths / 12);
if($timeSeconds < '2') {
return ''.$timeSeconds.' second ago';
} elseif($timeSeconds < '60') {
return ''.$timeSeconds.' seconds ago';
} elseif($timeMinutes < '2') {
return ''.$timeMinutes.' minute ago';
} elseif($timeMinutes < '60') {
return ''.$timeMinutes.' minutes ago';
} elseif($timeHours < '2') {
return ''.$timeHours.' hour ago';
} elseif($timeHours < '24') {
return ''.$timeHours.' hours ago';
} elseif($timeDays < '2') {
return ''.$timeDays.' day ago';
} elseif($timeDays < '7') {
return ''.$timeDays.' days ago';
} elseif($timeWeeks < '2') {
return ''.$timeWeeks.' week ago';
} elseif($timeWeeks < '4') {
return ''.$timeWeeks.' weeks ago';
} elseif($timeMonths < '2') {
return ''.$timeMonths.' month ago';
} elseif($timeMonths < '12') {
return ''.$timeMonths.' months ago';
} elseif($timeYears < '2') {
return ''.$timeYears.' year ago';
} elseif($timeYears > '1') {
return ''.$timeYears.' years ago';
} else {
return $timeSeconds;
}
} else {
return 'The Future';
}
}
Because your calculations are messed up. See one example and check all your formulas
<?
//same numbers, different formula
$checkTime=0;
echo (time()-$checkTime)/31536000; //45.094949422882 Years
?>
31536000 is the number of seconds in 1 year.
Even using that you will have to take care about leap years. We cant divide a timestamp by minutes then by hours then by days and so on. If you need accurate results the input has to be accurate as well.
Remember the famous Bi-Weekly and Twice Monthly payouts used commonly in USA? From a distance they both appear to mean the same thing but they don't. So dividing like your code is doing looses all that accuracy and when that difference is multiplied to 45 years it becomes substantial.
Fiddle
This question already has answers here:
Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...
(32 answers)
Closed 9 years ago.
I need to find time difference for like in facebook messages using php.
like: 2 weeks ago, 2 hr 30 mins ago, one second ago
My time format is "Y-m-d H:i:s"
Can Anyone help me with it?
Store the message created time in database then use below function :
function get_time_difference_php($created_time)
{
date_default_timezone_set('Asia/Calcutta'); //Change as per your default time
$str = strtotime($created_time);
$today = strtotime(date('Y-m-d H:i:s'));
// It returns the time difference in Seconds...
$time_differnce = $today-$str;
// To Calculate the time difference in Years...
$years = 60*60*24*365;
// To Calculate the time difference in Months...
$months = 60*60*24*30;
// To Calculate the time difference in Days...
$days = 60*60*24;
// To Calculate the time difference in Hours...
$hours = 60*60;
// To Calculate the time difference in Minutes...
$minutes = 60;
if(intval($time_differnce/$years) > 1)
{
return intval($time_differnce/$years)." years ago";
}else if(intval($time_differnce/$years) > 0)
{
return intval($time_differnce/$years)." year ago";
}else if(intval($time_differnce/$months) > 1)
{
return intval($time_differnce/$months)." months ago";
}else if(intval(($time_differnce/$months)) > 0)
{
return intval(($time_differnce/$months))." month ago";
}else if(intval(($time_differnce/$days)) > 1)
{
return intval(($time_differnce/$days))." days ago";
}else if (intval(($time_differnce/$days)) > 0)
{
return intval(($time_differnce/$days))." day ago";
}else if (intval(($time_differnce/$hours)) > 1)
{
return intval(($time_differnce/$hours))." hours ago";
}else if (intval(($time_differnce/$hours)) > 0)
{
return intval(($time_differnce/$hours))." hour ago";
}else if (intval(($time_differnce/$minutes)) > 1)
{
return intval(($time_differnce/$minutes))." minutes ago";
}else if (intval(($time_differnce/$minutes)) > 0)
{
return intval(($time_differnce/$minutes))." minute ago";
}else if (intval(($time_differnce)) > 1)
{
return intval(($time_differnce))." seconds ago";
}else
{
return "few seconds ago";
}
}
I'm looking for a function to convert dates presented in "X Hours ago" and "X minutes ago" back into a timestamp in php, anyone have a soulution to this?
strtotime already does this:
$timestamp = strtotime("8 hours ago");
See relative time format specifications for more info.
I helped someone on stackoverflow to write a function that does the reverse of this, here is the code, i'm sure if you deconstruct and reverse it, you will have your answer:
<?
$unix_time = 6734;
echo howLongAgo($unix_time);
function howLongAgo($time_difference){
// Swtich logic based on the time difference passed to this function, sets the english string and what number the difference needs to be divided by
switch($time_difference){
case ($time_difference < 60):
$string = " second";
break;
case ($time_difference >= 60 && $time_difference < 3600):
$string = " minute";
$divider = 60;
break;
case ($time_difference >= 3600 && $time_difference < 86400):
$string = " hour";
$divider = 3600;
break;
case ($time_difference >= 86400 && $time_difference < 2629743):
$string = " day";
$divider = 86400;
break;
case ($time_difference >= 2629743 && $time_difference < 31556926):
$string = " month";
$divider = 2629743;
break;
case ($time_difference >= 31556926):
$string = " year";
$divider = 31556926;
break;
}
// If a divider value is set during the switch, use it to get the actual difference
if($divider){$diff = round($time_difference / $divider);}else{$diff = round($time_difference);}
// If the difference does not equal 1, pluralize the final result EG: hours, minutes, seconds
if($diff != 1){$pluralize="s";}
// Concatenate all variables together and return them
$final = $diff . $string . $pluralize . " ago";
return $final;
}
?>
$hourago= "-1 hour";
$minago = "-2 minute";
$timestamp = strtotime($hourago.' '.$minago);
echo $timestamp;
or
$hourago= "-1";
$minago = "-2";
$timestamp = strtotime($hourago.' hour '.$minago.' minute');
echo $timestamp;
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I've got a piece of code that I created and I've been 'requiring_once' in to my PHP code for quite a while now. It works fine on my local PC, but when I upload it to my server it's coming up with the following error:
Parse error: syntax error, unexpected T_ELSE in /home/makequiz/public_html/nitpicker/func.php on line 47
Here's the function:
function howLongAgo($unix_time) {
// This function shows the unix time stamp
// as number of seconds, minutes, hours, days, months, years ago
// Get the time difference between time specified and the current unix time
$time_difference = time () - $unix_time;
$seconds_ago = $time_difference;
$minutes_ago = $time_difference / 60;
$hours_ago = $time_difference / 3600;
$days_ago = $time_difference / 86400;
$months_ago = $time_difference / 2629743;
$years_ago = $time_difference / 31556926;
if ($time_difference < 60) {
// Seconds Ago
return round ( $time_difference ) . ' Seconds Ago';
} else if ( ($time_difference >= 60) && ($time_difference < 3600) ) {
// Minutes Ago
if (round ( $time_difference / 60 ) == 1) {
return round ( $time_difference / 60 ) . " Minute Ago";
} else {
return round ( $time_difference / 60 ) . " Minutes Ago";
}
} else if ($time_difference >= 3600 && $time_difference < 86400) {
// Hours Ago
if (round ( $time_difference / 3600 ) == 1) {
return round ( $time_difference / 3600 ) . " Hour Ago";
} else {
return round ( $time_difference / 3600 ) . " Hours Ago";
}
} else if ($time_difference >= 86400 && $time_difference < 2629743) {
// Days Ago
if (round ( $time_difference / 86400 ) == 1) {
return round ( $time_difference / 86400 ) . " Day Ago";
} else {
return round ( $time_difference / 86400 ) . " Days Ago";
}
} else if ($time_difference >= 2629743 && $time_difference < 31556926) {
// Months Ago
if (round ( $time_difference / 2629743 ) == 1) {
return round ( $time_difference / 2629743 ) . " Month Ago";
} else {
return round ( $time_difference / 2629743 ) . " Months Ago";
}
} else if ($time_difference >= 31556926) {
// Years Ago
if (round ( $time_difference / 31556926 ) == 1) {
return round ( $time_difference / 31556926 ) . " Year Ago";
} else {
return round ( $time_difference / 31556926 ) . " Years Ago";
}
}
}
This error is coming up, even though I haven't called the function at all in my code.
Can anyone see any errors in the code, cause I can't :(
This would be a lot simpler using a switch/case logic scheme. I have re-coded what you had up there using switch/case and this might be a good intro for you to learn switch/case. You had some extra ( ) in one of the if statements above. I hope this helps, friend:
<?
$unix_time = 6734;
echo howLongAgo($unix_time);
function howLongAgo($time_difference){
// Swtich logic based on the time difference passed to this function, sets the english string and what number the difference needs to be divided by
switch($time_difference){
case ($time_difference < 60):
$string = " second";
break;
case ($time_difference >= 60 && $time_difference < 3600):
$string = " minute";
$divider = 60;
break;
case ($time_difference >= 3600 && $time_difference < 86400):
$string = " hour";
$divider = 3600;
break;
case ($time_difference >= 86400 && $time_difference < 2629743):
$string = " day";
$divider = 86400;
break;
case ($time_difference >= 2629743 && $time_difference < 31556926):
$string = " month";
$divider = 2629743;
break;
case ($time_difference >= 31556926):
$string = " year";
$divider = 31556926;
break;
}
// If a divider value is set during the switch, use it to get the actual difference
if($divider){$diff = round($time_difference / $divider);}else{$diff = round($time_difference);}
// If the difference does not equal 1, pluralize the final result EG: hours, minutes, seconds
if($diff != 1){$pluralize="s";}
// Concatenate all variables together and return them
$final = $diff . $string . $pluralize . " ago";
return $final;
}
?>
I think your problem may come from the difference between elseif and else if (note the space).
From the PHP website:
Note: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.
You have a syntax error in your code at line 47 (I am going to bet you are missing a semi-color or bracket at line 46.
It does not matter if you are calling the function or not, as the php parser will analyze the entire file upfront.
Couple of things..
did you change the file that it's included in when you loaded to your server?
try using include instead of require?