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】西暦から和暦を返す関数

Posted at

調べれば山ほど出てくる日本人御用達関数です。
どっかで拾った関数を魔改造したものなので似たものがある場合はご了承ください。

function get_wareki($year, $format = false, $gannen = false) {
  $gengoList = [
    ['name' => '令和', 'name_short' => 'R', 'year' => 2019],  // 2019-05-01,
    ['name' => '平成', 'name_short' => 'H', 'year' => 1989],  // 1989-01-08,
    ['name' => '昭和', 'name_short' => 'S', 'year' => 1926], // 1926-12-25'
    ['name' => '大正', 'name_short' => 'T', 'year' => 1912], // 1912-07-30
    ['name' => '明治', 'name_short' => 'M', 'year' => 1868], // 1868-01-25
  ];

  $gengo = array();
  foreach ($gengoList as $g) {
    if ($g['year'] <= $year) {
      $gengo = $g;
      break;
    }
  }

  $year = ($year - $gengo['year']) + 1;
  if ($year == 1 && $gannen) {
    $year = '元';
  }

  $out = $gengo['name'] . $year . '年';
  if ($format) {
    $out = $gengo['name_short'] . $year . '年';
  }
  return $out;
}

使い方

関数の第一引数に西暦を入れれば和暦が返ってきます。

echo get_wareki(2022)
// 令和4年

第二引数移行は任意ですが、第二引数をtrueにすると元号はアルファベットになります。

echo get_wareki(2022, true)
// R4年

第三引数は、1年の場合は元年に変更するオプションです。

echo get_wareki(2022, false, ture)
// 令和4年

echo get_wareki(2019, false, ture)
// 令和元年
0
0
0

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?