Skip to content

Instantly share code, notes, and snippets.

@44uk
Created September 10, 2013 03:58
Show Gist options
  • Save 44uk/6504793 to your computer and use it in GitHub Desktop.
Save 44uk/6504793 to your computer and use it in GitHub Desktop.
timeAgoInWords
<?php
function timeAgoInWords($datetime, $now = null){
if($now === null){ $now = date('Y-m-d H:i:s'); }
$units = array(
'y' => 31104000,
'm' => 2592000,
'd' => 86400,
'h' => 3600,
'i' => 60,
's' => 1,
);
$words = array(
'past' => '前',
'future' => '後',
'y' => '年',
'm' => 'ヶ月',
'd' => '日',
'h' => '時間',
'i' => '分',
's' => '秒',
);
$prefix = '約';
$time_ago = '';
$sec = strtotime($datetime);
$now_sec = strtotime($now);
$diff_sec = $now_sec - $sec;
$direction = $diff_sec > 0 ? $words['past'] : $words['future'];
$decrease_sec = $diff_sec;
$divides = array('y' => 0, 'm' => 0, 'd' => 0, 'h' => 0, 'i' => 0, 's' => 0);
foreach($divides as $key => $val){
$divides[$key] = (int)($decrease_sec / $units[$key]);
$decrease_sec %= $units[$key];
}
$time_ago = '';
$keys = array_keys($divides);
foreach($keys as $key){
if($divides[$key] > 0){
$time_ago .= $divides[$key] . $words[$key];
}
}
$time_ago = $prefix . $time_ago . $direction;
return $time_ago;
}
echo timeAgoInWords(date('Y-m-d H:i:s', time() - 186400));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment