Convert datetime format from Mysql to a more friendly format like: "3 days 12 hours ago"
i have some dates retrived using php from my mysq开发者_如何学Gol server in the conventional format: 2011-05-13 12:22:11 , how can i convert this to: 3 days and 12 hours ago. Thanks a lot!
For your troubles (source) - the internet is awesome:
/* takes an argument in unix time (seconds) */
function time_since($original) {
// array of time period chunks
$chunks = array(
array(60 * 60 * 24 * 365 , 'year'),
array(60 * 60 * 24 * 30 , 'month'),
array(60 * 60 * 24 * 7, 'week'),
array(60 * 60 * 24 , 'day'),
array(60 * 60 , 'hour'),
array(60 , 'minute'),
);
$today = time(); /* Current unix time */
$since = $today - $original;
// $j saves performing the count function each time around the loop
for ($i = 0, $j = count($chunks); $i < $j; $i++) {
$seconds = $chunks[$i][0];
$name = $chunks[$i][1];
// finding the biggest chunk (if the chunk fits, break)
if (($count = floor($since / $seconds)) != 0) {
// DEBUG print "<!-- It's $name -->\n";
break;
}
}
$print = ($count == 1) ? '1 '.$name : "$count {$name}s";
if ($i + 1 < $j) {
// now getting the second item
$seconds2 = $chunks[$i + 1][0];
$name2 = $chunks[$i + 1][1];
// add second item if it's greater than 0
if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
$print .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";
}
}
return $print;
}
echo time_since(strtotime('2011-05-13 12:22:11')); // 1 day, 2 hours
You can split it into arrays, and then use the mktime function to manually rebuild a timestamp that PHP can recognize.
$str = "2011-05-13 12:22:11";
//Seperate the Date and Time components into an array
$detail_array = explode(" ", $str);
//Seperate each the Year, Month and Day
$date_array = explode("-", $detail_array[0]);
//Seperate the Hour, Minute and Second
$time_array = explode(":", $detail_array[1]);
//Recompile the components into the correct order to produce a timestamp
$timestamp = mktime($time_array[0], $time_array[1], $time_array[2], $date_array[1], $date_array[2], $date_array[0]);
//Confirm the timestamp produces the original string
echo "Timestamp Test: " . date("Y-m-d h:i:s", $timestamp) . "<br />";
//Determine how long ago the timestamp was in seconds
$age = time() - $timestamp;
$days_old = round($age / 86400, 0);
$hours_old = round(($age - ($days_old * 86400)) / 3600, 0);
echo "$days_old day/s and $hours_old hour/s ago";
This might be of good use to you, "Handy Time Phrases in PHP".
http://danlamanna.com/portfolio/?p=51
You would need to subtract this date from the current date.
Use DateTime::diff for the purpose. This will return you a DateInterval Object which you can readily convert to the form you want to present it in.
精彩评论