This Article will help to display date/time difference like orkut, twitter, FB,. The code snippet i have written is to show date/time difference between current and stored date-time from database. I did check most of web for a similar function, got lots and then finally created an optimized version for a specific requirement. I wrote a PHP function which returns date difference in number of years, days, hours and even seconds.
Every bit of time is valuable, so i didn’t want to lose any second .
Output of function will be like ,
’5 days before’, ’2 months, 3 days before, ’2 hour before’
Following is the source code,
function diffofdate($d1, $d2){ $d1 = (is_string($d1) ? strtotime($d1) : $d1); $d2 = (is_string($d2) ? strtotime($d2) : $d2); $diff_secs = abs($d1 - $d2); $base_year = min(date("Y", $d1), date("Y", $d2)); $diff = mktime(0, 0, $diff_secs, 1, 1, $base_year); $displaydate = ""; if(date("Y", $diff) - $base_year > 0) { $displaydate = (date("Y", $diff) - $base_year) . " year"; if(date("Y", $diff) - $base_year> 1)$displaydate .= "s"; if(date("n", $diff) - 1 > 0) $displaydate .= ", " . (date("n", $diff) - 1) . " month"; if((date("n", $diff) - 1) > 1)$displaydate .= "s"; $displaydate .= " before"; } else if(date("n", $diff) - 1 > 0) { $displaydate .= (string)(date("n", $diff) - 1) . " month"; if((date("n", $diff) - 1) > 1)$displaydate .= "s"; if(date("j", $diff) - 1 > 0) $displaydate .= ", " . (date("j", $diff) - 1) . " day"; if((date("j", $diff) - 1) > 1)$displaydate .= "s"; $displaydate .= " before"; } else if(date("j", $diff) - 1 > 0) { $displaydate .= (string)(date("j", $diff) - 1) . " day"; if((date("j", $diff) - 1) > 1)$displaydate .= "s"; if((int) date("G", $diff) > 0) $displaydate .= ", " . date("G", $diff) . " hour"; if(date("G", $diff) > 1)$displaydate .= "s"; $displaydate .= " before"; } else if((int) date("G", $diff) > 0) { $displaydate .= (string)(date("G", $diff)). " hour"; if(date("G", $diff) > 1)$displaydate .= "s"; if((int) date("i", $diff) > 0) $displaydate .= ", " . date("i", $diff) . " minute"; if(date("i", $diff) > 1)$displaydate .= "s"; $displaydate .= " before"; } else if((int) date("i", $diff) > 0){ $displaydate .= date("i", $diff) . " minute"; if(date("i", $diff) > 1)$displaydate .= "s"; $displaydate .= " ago" } else if((int) date("s", $diff) > 0){ $displaydate .= date("s", $diff) . " second"; if(date("s", $diff) > 1) $displaydate .= "s";$displaydate .= " ago"; } else $displaydate = "A moment ago."; return $displaydate; }
So when we call the above function we need to call
diffofdate(date('Y-m-d H:i:s'),$dates)
where $date is the one we stored earlier which is in the format as current date (date(‘Y-m-d H:i:s’)).
Issues will come if you have a web-farm scenario with multiple webservere in different geo-location. In those scenarios we need to store the timezone Offset as well or store UTC time.
Feel free to ping me for any clarification.
Comments (2)