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 3 years have passed since last update.

日付関数と誕生日を用いて、年齢を算出する方法(PHP)

Posted at

外部のAPIを叩いて、年齢を算出する処理を書く必要があったので、その時に実行した関数のことを記録しておく。

答えのコード

sample.php
date_default_timezone_set('Asia/Tokyo');
$currentDate = date('Y/m/d');  //2020-01-29
$birthday = "あなたの誕生日 例:1980-01-01";
$fc = (int)date('Ymd', strtotime($currentDate)); //20200129
$fb = (int)date('Ymd', strtotime($birthday));    // 19800101
$age = (int)(($fc - $fb) / 10000);  //40

解説

まず、タイムゾーンの設定をして基準の時間を日本にします。

date_default_timezone_set('Asia/Tokyo');

次に、date関数で現在の日時の算出します。加えて、あなたの誕生日を入力してください。
date関数は第一引数で指定したフォーマットでその日時を出力します。
この時のデータ型はstringです。

$currentDate = date('Y/m/d');
$birthday = "あなたの誕生日 例:1980-01-01";

次に、先ほどの$currentDate$birthdaystrtotimeでタイムスタンプとして出力したものをint型に書き換えます。
この時dateのフォーマットをYmdに指定することで日付を数値として出力させることができます!
例えば、1980-01-0119800101として変換されます。
加えて、int型に変換することで整数値かつ数値として変換されます。

$fc = (int)date('Ymd', strtotime($currentDate));
$fb = (int)date('Ymd', strtotime($birthday));

最後に、引き算をして10000で割ります。

引き算のフロー: 20200129 - 19800101 = 400028
10000でわる: 400028 / 10000 = 40.0028

つまり、西暦の足し算で年齢の10000倍算出して、それを10000で割ることで年齢だけを整数値で変数に納めています。

$age = (int)(($fc - $fb) / 10000);
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?