Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
元号取得関数(明治〜令和)
<?php
function get_gengou( $time, $format = '%s%s' ) {
list( $y, $m, $d ) = explode( ' ', date( 'Y m d', is_numeric( $time ) ? $time : strtotime( $time ) ) );
$gengou = '';
if ( $y < 1868 ) {
return $gengou;
}
if ( $y >= 1868 && $y < 1912 ) {
$gengou = '明治';
} else if ( $y >= 1913 && $y < 1926 ) {
$gengou = '大正';
} else if ( $y >= 1927 && $y < 1989 ) {
$gengou = '昭和';
} else if ( $y >= 1990 && $y < 2019 ) {
$gengou = '平成';
} else if ( $y >= 2020 ) {
$gengou = '令和';
} else if ( $y == 1912 ) {
if ( $m < 7 ) {
$gengou = '明治';
} else if ( $m > 7 ) {
$gengou = '大正';
} else {
if ( $d <= 29 ) {
$gengou = '明治';
} else {
$gengou = '大正';
}
}
} else if ( $y == 1926 ) {
if ( $m < 12 ) {
$gengou = '大正';
} else {
if ( $d <= 24 ) {
$gengou = '大正';
} else {
$gengou = '昭和';
}
}
} else if ( $y == 1989 ) {
if ( $m > 1 ) {
$gengou = '平成';
} else {
if ( $d <= 7 ) {
$gengou = '昭和';
} else {
$gengou = '平成';
}
}
} else if ( $y == 2019 ) {
if ( $m > 4 ) {
$gengou = '令和';
} else {
$gengou = '平成';
}
}
if ( $gengou === '明治' ) {
$year = $y - 1867;
} else if ( $gengou === '大正' ) {
$year = $y - 1911;
} else if ( $gengou === '昭和' ) {
$year = $y - 1925;
} else if ( $gengou === '平成' ) {
$year = $y - 1988;
} else if ( $gengou === '令和' ) {
$year = $y - 2018;
}
if ( $year == 1 ) {
$year = '元';
}
return sprintf( $format, $gengou, $year );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.