Skip to content

Instantly share code, notes, and snippets.

@krishnakummar
Created June 29, 2011 12:34
Show Gist options
  • Save krishnakummar/1053741 to your computer and use it in GitHub Desktop.
Save krishnakummar/1053741 to your computer and use it in GitHub Desktop.
Humanize date differences in PHP (like facebook - Eg: 2 days ago, 14 hours ago, few seconds ago).
#!/usr/bin/env php
# This function prints the difference between two php datetime objects
# in a more human readable form
# inputs should be like strtotime($date)
# Adapted from https://gist.github.com/207624 python version
function humanizeDateDiffference($now,$otherDate=null,$offset=null){
if($otherDate != null){
$offset = $now - $otherDate;
}
if($offset != null){
$deltaS = $offset%60;
$offset /= 60;
$deltaM = $offset%60;
$offset /= 60;
$deltaH = $offset%24;
$offset /= 24;
$deltaD = ($offset > 1)?ceil($offset):$offset;
} else{
throw new Exception("Must supply otherdate or offset (from now)");
}
if($deltaD > 1){
if($deltaD > 365){
$years = ceil($deltaD/365);
if($years ==1){
return "last year";
} else{
return "<br>$years years ago";
}
}
if($deltaD > 6){
return date('d-M',strtotime("$deltaD days ago"));
}
return "$deltaD days ago";
}
if($deltaD == 1){
return "Yesterday";
}
if($deltaH == 1){
return "last hour";
}
if($deltaM == 1){
return "last minute";
}
if($deltaH > 0){
return $deltaH." hours ago";
}
if($deltaM > 0){
return $deltaM." minutes ago";
}
else{
return "few seconds ago";
}
}
@vassyz
Copy link

vassyz commented Apr 16, 2014

May I ask why you need this in the code?

if($deltaD > 6){
  return date('d-M',strtotime("$deltaD days ago"));
} 

It will return something like '07-Apr'. What would that achieve?
Thanks.

@vassyz
Copy link

vassyz commented Apr 16, 2014

I also changed line 18 to use floor:

$deltaD = ($offset > 1)?floor($offset):$offset;

Let's say that something happend yesterday at 1 and your current time is 2. Would you call one hour and a day two days ago or one day ago? One day ago made more sense in my app.

Cheers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment