Dalam PHP, anda boleh menukar cap masa kepada rentetan masa berlalu menggunakan fungsi time_elapsed_string().
function time_elapsed_string($datetime, $full = false) { // Get the current date and time $now = new DateTime; // Create a DateTime object from the input timestamp $ago = new DateTime($datetime); // Calculate the difference between the current time and the input timestamp $diff = $now->diff($ago); // Convert weeks and days to days $diff->w = floor($diff->d / 7); $diff->d -= $diff->w * 7; // Create an array of time units and their corresponding English names $string = [ 'y' => 'year', 'm' => 'month', 'w' => 'week', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; // Iterate through the time units and add them to the output string if they are greater than 0 foreach ($string as $k => &$v) { if ($diff->$k) { $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : ''); } else { unset($string[$k]); } } // If the `$full` parameter is false, only return the first time unit if (!$full) $string = array_slice($string, 0, 1); // Return the formatted time elapsed string return $string ? implode(', ', $string) . ' ago' : 'just now'; }
echo time_elapsed_string('2013-05-01 00:22:35'); // Output: 4 months ago echo time_elapsed_string('@1367367755'); // Output: 4 months ago echo time_elapsed_string('2013-05-01 00:22:35', true); // Output: 4 months, 2 weeks, 3 days, 1 hour, 49 minutes, 15 seconds ago
Atas ialah kandungan terperinci Bagaimana untuk Menukar Cap Waktu PHP kepada Rentetan 'Masa Lalu' yang Boleh Dibaca Manusia?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!