JavaScriptは他の言語に比べ、Dateオブジェクトや日付に関する機能が非常に少ないです。ですので、必要な機能は自前で実装する必要があります。今回は年齢の算出に関して、引数の方や状態別にご紹介します。
yyyyMMdd, yyyy/MM/dd等文字列から算出// yyyyMMdd形式限定、処理日時点の年齢 function calcAge(birthdate) { var today = new Date(); targetdate = today.getFullYear() * 10000 + (today.getMonth() + 1) * 100 + today.getDate(); return (Math.floor((targetdate - birthdate) / 10000)); } よく見かけるオーソドックスなアルゴリズムです。割とシンプルです。
// yyyyMMdd, yyyy/MM/dd, yyyy-MM-dd形式に対応。 // 基準日指定可能。基準日を指定しなければ処理日を基準日とする function calcAge(birthdate, targetdate) { birthdate = birthdate.replace(/[/-]/g, ""); if (targetdate) { targetdate = targetdate.replace(/[/-]/g, ""); } else { var today = new Date(); targetdate = today.getFullYear() * 10000 + (today.getMonth() + 1) * 100 + today.getDate(); } return (Math.floor((targetdate - birthdate) / 10000)); } 少し汎用性を持たせました。それでもまぁまぁシンプルです。
年月日がばらばらに与えられ、かつ月・日が2桁の文字列であると保証されない場合function calcAge(y, m, d) { var birthdate = y * 10000 + m * 100 + d; var today = new Date(); var targetdate = today.getFullYear() * 10000 + (today.getMonth() + 1) * 100 + today.getDate(); return (Math.floor((targetdate - birthdate) / 10000)); } y, m, dがばらばらに与えられた場合に、「yyyyMMdd」と同等の形式をどう作るかの話で、単に年を10000倍、月を100倍にして加算すればそれで済むよねという話。処理内容は「yyyyMMdd」形式の処理のときとほとんど同じです。
Dateオブジェクトから算出function calcAge(birthdate, targetdate) { var age = targetdate.getFullYear() - birthdate.getFullYear(); var birthday = new Date(targetdate.getFullYear(), birthdate.getMonth(), birthdate.getDate()); if (targetdate < birthday) { age--; } return age; } Dateオブジェクトから算出する場合は、わざわざ年・月・日の3つの値を取得して10000万倍・100倍して加算するという方法より、「年を引き誕生日が来ていなかったら1つ引く」というアルゴリズムにするのがシンプルで自然でしょう。
// ついでに数え年の算出機能もつけた function calcAge(birthdate, targetdate, is数え年) { var age = targetdate.getFullYear() - birthdate.getFullYear(); if (is数え年) { age++; } else { var birthday = new Date(targetdate.getFullYear(), birthdate.getMonth(), birthdate.getDate()); if (targetdate < birthday) { age--; } } return age; } ちなみに、birthdayは誕生日。生年月日の月と日が同じ日で、原則毎年訪れる(閏日生まれは例外)。birthdateは生年月日。あまり聞きなれない単語ではありますが、生年月日を表す変数にはその意味を明確にするために、birthdateを使うべきだと思います。
日付と時刻の計算 (JavaScript) - MSDN |
Code Tips >