0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【PHP】西暦を和暦に変換する関数

Last updated at Posted at 2023-08-10

PHPで西暦を和暦に変換する処理を書く機会があったため、備忘録として残します。

function convertToJapaneseEra($year) {
    try {
        if ($year < 1868) {
            throw new Exception("1868年より前の年は変換できません。");
        }
    
        $eraData = [
            ["name" => "令和", "start" => 2019],
            ["name" => "平成", "start" => 1989],
            ["name" => "昭和", "start" => 1926],
            ["name" => "大正", "start" => 1912],
            ["name" => "明治", "start" => 1868]
        ];
    
        $japaneseYear = "";
        
        foreach ($eraData as $era) {
            if ($year >= $era["start"]) {
                $japaneseYear = $era["name"] . ($year - $era["start"] + 1);
                if ($year === $era["start"]) {
                    $japaneseYear .= "元年";
                } else {
                    $japaneseYear .= "年";
                }
                break;
            }
        }

        return $japaneseYear;

    } catch (Exception $e) {
        echo "エラー: " . $e -> getMessage();
    }
}
使用例
echo convertToJapaneseEra(2019); // 令和元年
echo convertToJapaneseEra(1192); // エラー: 1868年より前の年は変換できません。
0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?