Skip to content

Instantly share code, notes, and snippets.

@wgkoro
Last active February 26, 2018 22:35
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wgkoro/4985763 to your computer and use it in GitHub Desktop.
Save wgkoro/4985763 to your computer and use it in GitHub Desktop.
TwitterやFacebookのように投稿時間を「X秒前」や「X日前」といった文字列に変換。
<?php
/**
* X秒前、X分前、X時間前、X日前などといった表示に変換する。
* 一分未満は秒、一時間未満は分、一日未満は時間、
* 31日以内はX日前、それ以上はX月X日と返す。
* X月X日表記の時、年が異なる場合はyyyy年m月d日と、年も表示する
*
* @param <String> $time_db strtotime()で変換できる時間文字列 (例:yyyy/mm/dd H:i:s)
* @return <String> X日前,などといった文字列
**/
function convert_to_fuzzy_time($time_db){
$unix = strtotime($time_db);
$now = time();
$diff_sec = $now - $unix;
if($diff_sec < 60){
$time = $diff_sec;
$unit = "秒前";
}
elseif($diff_sec < 3600){
$time = $diff_sec/60;
$unit = "分前";
}
elseif($diff_sec < 86400){
$time = $diff_sec/3600;
$unit = "時間前";
}
elseif($diff_sec < 2764800){
$time = $diff_sec/86400;
$unit = "日前";
}
else{
if(date("Y") != date("Y", $unix)){
$time = date("Y年n月j日", $unix);
}
else{
$time = date("n月j日", $unix);
}
return $time;
}
return (int)$time .$unit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment