1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【令和も対応】PHPで和暦⇔西暦変換

Last updated at Posted at 2021-09-06

西暦を和暦に変換する処理を書く機会があって、また必要になるかも。
と思い、汎用的に使い回せるよう、関数を作成してみました。

PHPで、西暦⇔和暦変換をする機会のある方は、参考にしてください。
そんな難しくないです。

PHPで西暦 → 和暦

wareki.php
// 西暦 => 和暦
function wareki($year) {

    $eras = array(
        array('year' => 2018, 'name' => '令和'),
        array('year' => 1988, 'name' => '平成'),
        array('year' => 1925, 'name' => '昭和'),
        array('year' => 1911, 'name' => '大正'),
        array('year' => 1867, 'name' => '明治')
    );

    foreach($eras as $era) {
        if ($year > $era['year']) {
            $era_year = $year - $era['year'];
            return $era['name'] . ($era_year === 1 ? '元年' : $era_year . '年');
        }
    }

    return null;
}

echo wareki(2019); // 令和元年

PHPで和暦 → 西暦

seireki.php
// 和暦 => 西暦
function seireki($wareki_year) {
    $wareki_year = str_replace('元年', '1年', mb_convert_kana($wareki_year, 'n'));

    $era_start_years = array(
        '明治' => 1867,
        '大正' => 1911,
        '昭和' => 1925,
        '平成' => 1988,
        '令和' => 2018
    );

    if(preg_match('!^(明治|大正|昭和|平成|令和)([0-9]+)年$!', $wareki_year, $matches)) {
        $era_name = $matches[1];
        $year = intval($matches[2]) + $era_start_years[$era_name];
        return $year . '年';
    }

    return null;
}

echo seireki('平成元年'); // 1989年

その他の記事

PHPで日、月、年の加算と減算方法
https://qiita.com/thiagomatsui/items/619775a96dce38bc5060

参考サイト

1
2
2

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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?