タイトルのままです。
普段Laravelを使っていて、最近のバージョンではデフォルトでCarbonが入っているので、diffForHumans()
を使うとある程度時間差を見やすく変換してくれますが、今回具体的に年齢と日数を取得する必要があったのでクラスを作ってみました。
- ◯年◯ヶ月◯日
- ◯◯◯日
とかなら比較的簡単だったけど、年と日数に分ける必要があったのでひと手間。
レアケースなので、再利用性は低いと思いますが、折角なので上げておきます。
仕様
誕生日と現在日から、生後◯歳と◯日を出力。うるう日もカウント。
誕生日 '2015-02-12'
現在日 '2016-03-12'
出力 '生後1歳と29日'
クラス
class ConvertBirthday
{
private $birthday;
public function __construct($birthday)
{
$this->birthday = new DateTime($birthday);
}
public function yearDays($today_param = null)
{
$today = new DateTime($today_param);
if(!$today){
return "";
}
//現在の歳を計算
$years = $this->calcYears($today);
//最後の誕生日から今日までの日数を計算
$days = $this->calcDays($today);
//文字列に整える
$year_days = $this->genString($years, $days);
return $year_days;
}
private function calcYears($today)
{
$years = $today->diff($this->birthday)->y;
return $years;
}
private function calcDays($today)
{
$temp_birthday = $this->birthday->format(date('Y')."-m-d");
$temp_today = $today->format(date('Y')."-m-d");
//誕生日が1/1~今日の間の場合、今年の誕生日を取得
if($temp_birthday <= $temp_today){
$last_birthday_year = $today->format("Y");
}
//誕生日が明日~12/31の間の場合、昨年の誕生日を取得
else {
$last_birthday_year = $today->format("Y") - 1;
}
$last_birthday = new DateTime($this->birthday->format( $last_birthday_year."-m-d" ));
$days = $last_birthday->diff($today)->format('%a');
return $days;
}
private function genString($years, $days)
{
$year_str = "";
if(!empty($years)){
$year_str = $years."歳";
}
$day_str = "0日";
if(!empty($days)){
$day_str = $days."日";
}
$separater = "";
if(!empty($year_str)){
$separater = "と";
}
return "生後{$year_str}{$separater}{$day_str}";
}
}
使い方
$birthday = "2010-01-01";
$convert = new ConvertBirthday($birthday);
//現在日までの日数
echo $convert->yearDays();
//指定した日までの日数
$date = '2019-06-12';
echo $convert->yearDays($date); //生後9歳と162日
作ってみて
オブジェクト指向がまだいまいち掴みきれなくて、これでいいのかよくわかってません。
バグもあるかもしれません。