【JavaScript】誕生日から現時点の年齢を求める

誕生日(年月日)から現時点の年齢を求めるサンプルです。

 

var formObj = '';

var zeroFormat = function(v, n) {
vl = String(v).length;
if (n > vl) {
return (new Array((n - vl) + 1).join(0)) + v;
} else {
return v;
}
};

var ageCalculator = function(year, month, day) {
var dateObj = new Date(),
today = parseInt('' + dateObj.getFullYear() + zeroFormat(dateObj.getMonth() + 1, 2) + zeroFormat(dateObj.getDate(), 2)),
birthday = parseInt('' + year + zeroFormat(month, 2) + zeroFormat(day, 2));

formObj.age.value = parseInt((today - birthday) / 10000);
};

var changeDate = function(mode) {
var tYear = formObj.year,
tMonth = formObj.month,
tDays = formObj.days,
selectY = tYear.options[tYear.selectedIndex].value,
selectM = tMonth.options[tMonth.selectedIndex].value,
selectD = tDays.options[tDays.selectedIndex].value,
dateObj,
gDate,
i;

if (mode === 'date') {
dateObj = new Date(selectY, selectM, 0);
gDate = dateObj.getDate();

tDays.length = 0;

for (i = 1 ;i <= gDate; i++) {
tDays.options[i] = new Option(i, i);
}

tDays.removeChild(tDays.options[0]);

if (selectD > tDays.length) {
tDays.options[tDays.length - 1].selected = true;
} else {
tDays.options[selectD - 1].selected = true;
}
}

ageCalculator(selectY, selectM, selectD);
};

formObj = document.form1;

// 年の選択変更時
formObj.year.onchange = function() {
changeDate('days');
};

// 月の選択変更時
formObj.month.onchange = function() {
changeDate('date');
};

// 日の選択変更時
formObj.days.onchange = function() {
changeDate('age');
};
</script>

 

ブレードファイルの方はこのように作っています。

<li class="form-wrapper__item">
<dl class="clearfix">
<dt class="form-wrapper__item__title MH">
<span class="form-wrapper__item__title__text">
生年月日
</span>
</dt>
<dd class="form-wrapper__item__form MH">
<div class="form-wrapper__item__form__year">
<select name="year" id="year" class="select">
<option value="">
選択してください
</option>
@for ($i = 1980; $i <= 2005; $i++)
<option value="{{ $i }}"@if(old('year') == $i) selected @endif>{{ $i }}</option>
@endfor
</select>
</div><!--
--><ul class="form-wrapper__item__form__day clearfix"><!--
--><li class="form-wrapper__item__form__day__item">
<select name="month" id="month" class="select">
<option value="">
--月
</option>
@for ($i = 1; $i <= 12; $i++)
<option value="{{ $i }}"@if(old('month') == $i) selected @endif>{{ $i }}</option>
@endfor
</select>
</li><!--
--><li class="form-wrapper__item__form__day__item">
<select name="days" id="days" class="select">
<option value="">
--日
</option>
@for ($i = 1; $i <= 31; $i++)
<option value="{{ $i }}"@if(old('days') == $i) selected @endif>{{ $i }}</option>
@endfor
</select>
</li><!--
--></ul>
@include('inquiry.error', ['name' => 'year'])
@include('inquiry.error', ['name' => 'month'])
@include('inquiry.error', ['name' => 'days'])
</dd>
</dl>
</li>

 

 

 

 

Twitterでフォローしよう

おすすめの記事