未だに明治やら大正やら昭和やら平成やら日本の元号がちょくちょく利用されますが、素晴らしいdate()関数の拡張クラスを発見したので。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
/* // 日時用汎用クラス ---------------------------------------------------------------- */ class DatetimeUtility { private static $gengoList = [ ['name' => '令和', 'name_short' => 'R', 'timestamp' => 1556636400], // 2019-05-01, ['name' => '平成', 'name_short' => 'H', 'timestamp' => 600188400], // 1989-01-08, ['name' => '昭和', 'name_short' => 'S', 'timestamp' => -1357635600], // 1926-12-25' ['name' => '大正', 'name_short' => 'T', 'timestamp' => -1812186000], // 1912-07-30 ['name' => '明治', 'name_short' => 'M', 'timestamp' => -3216790800], // 1868-01-25 ]; private static $weekJp = [ 0 => '日', 1 => '月', 2 => '火', 3 => '水', 4 => '木', 5 => '金', 6 => '土', ]; private static $ampm = [ 'am' => '午前', 'pm' => '午後', ]; public static function date($format, $timestamp = null) { $gengo = array(); $timestamp = is_null($timestamp) ? time() : $timestamp; if (preg_match('/[J|b|K|k]/', $format)) { foreach (self::$gengoList as $g) { if ($g['timestamp'] <= $timestamp) { $gengo = $g; break; } } if (empty($gengo)) { throw new Exception('Can not be converted to a timestamp : '.$timestamp); } } // J : 元号 if (strpos($format, 'J') !== false) { $format = preg_replace('/J/', $gengo['name'], $format); } // b : 元号略称 if (preg_match('/b/', $format)) { $format = preg_replace('/b/', '¥¥' . $gengo['name_short'], $format); } // K : 和暦用年(元年表示) if (preg_match('/K/', $format)) { $year = date('Y', $timestamp) - date('Y', $gengo['timestamp']) + 1; $year = $year == 1 ? '元' : $year; $format = preg_replace('/K/', $year, $format); } // k : 和暦用年 if (preg_match('/k/', $format)) { $year = date('Y', $timestamp) - date('Y', $gengo['timestamp']) + 1; $format = preg_replace('/k/', $year, $format); } // x : 日本語曜日 if (preg_match('/x/', $format)) { $w = date('w', $timestamp); $format = preg_replace('/x/', self::$weekJp[$w], $format); } // 午前午後 if (preg_match('/E/', $format)) { $a = date('a', $timestamp); $format = preg_replace('/E/', $ampm[$a], $format); } return date($format, $timestamp); } } |
引用元:PHPで和暦・日本語曜日を使う