【PHP】日付のよく使用する表記パターンの関数
2023-06-07 714 1770<日付表記パターン>
<?php
function viewDate($date,$style = ""){
$WEEK = array("日","月","火","水","木","金","土");
if(isset($date)){
$date = substr($date,0,10);
$date = str_replace("/","-",$date);
if($date != "0000-00-00"){
list($y,$m,$d) = explode("-",$date);
$w = date("w", strtotime($date));
$n = ltrim($m,0);
$j = ltrim($d,0);
switch($style){
case 1: $str = "{$y}年{$n}月"; break;
case 2: $str = "{$n}月{$j}日({$WEEK[$w]})"; break;
case 3: $str = "{$y}/{$m}/{$d}"; break;
case 4: $str = "{$n}/{$j}({$WEEK[$w]})"; break;
case 5: $str = "{$y}"; break;
case 6: $str = "{$n}月{$j}日"; break;
case 7: $str = "{$m}/{$n}/{$j}"; break;
case 8: $str = "{$y}年{$n}月{$j}日({$WEEK[$w]})"; break;
case 9: $str = "{$y}/{$n}/{$j}({$WEEK[$w]})"; break;
default: $str = "{$y}年{$n}月{$j}日";
}
return $str;
}
}
}
$date = "2023-06-07 12:00:00";
echo viewDate($date,8); //結果 2023年6月7日(水)
?>
PHP8の環境下ではmktime関数のタイムスタンプ取得はエラーが起きました。
曜日の取得はstrtotime関数で行うのが簡単。
<?php
//php8で期限切れ
$timestamp = mktime(0, 0, 0, $m, $d, $y);
$w = date("w", $timestamp);
//曜日の取得はstrtotimeが明瞭
$w = date("w", strtotime($date));
?>