Hey, Im looking to create a function which will compare a time with the current time and get the difference. These will be in the same format as the date() produces. If the difference is more than 24 hours then I want the function to return the date in the DD/MM/YYYY format. If it is less than 24 hours ago then I want the function to return something like: "4 hours, 18 minutes, 9 seconds ago" How can I do this? Thanks
I wrote this a while ago. It does not EXACTLY do what you want, but it should get you started. function calc_date_diff($timestamp_past = false, $timestamp_future = false, $years = true, $months = true, $days = true, $hours = true, $mins = true, $secs = true) { // Use current time if parameter is FALSE. if (!$timestamp_past) $timestamp_past = time(); if (!$timestamp_future) $timestamp_future = time(); // Attempt to convert strings to timestamp if necessary. $timestamp_future = is_string($timestamp_future) ? strtotime($timestamp_future) : intval($timestamp_future); $timestamp_past = is_string($timestamp_past) ? strtotime($timestamp_past) : intval($timestamp_past); $diff = $timestamp_future - $timestamp_past; $calc_times = array(); $timeleft = array(); // Prepare array, depending on the output we want to get. if ($years) $calc_times[] = array('Year', 'Years', 31104000); if ($months) $calc_times[] = array('Month', 'Months', 2592000); if ($days) $calc_times[] = array('Day', 'Days', 86400); if ($hours) $calc_times[] = array('Hour', 'Hours', 3600); if ($mins) $calc_times[] = array('Minute', 'Minutes', 60); if ($secs) $calc_times[] = array('Second', 'Seconds', 1); foreach ($calc_times AS $timedata) { list($time_sing, $time_plur, $offset) = $timedata; if ($diff >= $offset) { $left = floor($diff / $offset); $diff -= ($left * $offset); $timeleft[] = "{$left} ". ($left == 1 ? $time_sing : $time_plur); } } return $timeleft ? ($timestamp_future > $timestamp_past ? null : '-') . implode(', ', $timeleft) : 0; } PHP:
He would need an a conditional statement in the code to determine if the difference is more than 24 hours and then if so, he could present the actual date. If less than 24 hours difference, what's printed would be the string (4 hours ago...)
Great, but you still haven't really thought about it, you cant express the time inbetween two dates as a date itself, it makes no sense.
Great, glad you could find something. Krakjoe my point was just to say that he may have made an error expressing what he wanted and that generally he could create the final output of a date. Someone who knows PHP, which I'm assuming you do, could wade through any errors of expressing requirements and complete a script that reflects his needs or at least advise him of alternatives instead of just saying IMPOSSIBLE. I mean doesn't that happen to you frequently when working with clients?
Just to clear things up - I wasnt looking to express the difference as DD/MM/YYYY - I wanted to express it as "x hours, x minutes and x seconds). Thanks