Calculation of time elapsed in PHP
- 2021年1月18日
- 技術情報
Today I would like to write some code about calculating time elapsed in PHP. Especially if we want to know the elapsed time of inserted records (seconds, minutes, hours , days etc).
For example – Posted 1 週前、3 時間前、50 分間前、30秒間前。
Here is our function to calculate the time eclipse
<?php
function time_elapsed($datetime) {
$now = new DateTime;
$ago = new DateTime($datetime);
//getting the time differences.
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7); //week
$diff->d -= $diff->w * 7; //day
//string arrays of formats
$string = array(
'y' => '年',
'm' => '月',
'w' => '週',
'd' => '日',
'h' => '時間',
'i' => '分',
's' => '秒',
);
//mapping the time difference and format
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v;
} else {
unset($string[$k]);
}
}
//only getting the first array key and value
$string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . '前' : 'ちょうど今';
}
I have included the comments in code so that you can be able to understand it. Let’s call our function to test.
echo time_elapsed("2020-12-06 11:24:25"); //output 1 月前
echo time_elapsed(date("Y-m-d H:i:s")); //output ちょうど今
PS. we have to care about our server timezone when we are dealing with Datetime functions
By Yuuma
yuuma at 2021年01月18日 04:56:29