|
61 | 61 | age = getAge(year, month, day),
|
62 | 62 | allowedAgeRange = ($el.valAttr('age-range') || '0-124').split('-');
|
63 | 63 |
|
| 64 | + $el.trigger('ageCalculated', [age]); |
| 65 | + |
64 | 66 | if (allowedAgeRange.length !== 2 || !$.isNumeric(allowedAgeRange[0]) || !$.isNumeric(allowedAgeRange[1])) {
|
65 | 67 | throw new Error('Date range format invalid');
|
66 | 68 | }
|
|
71 | 73 | errorMessageKey: 'badDate'
|
72 | 74 | });
|
73 | 75 |
|
74 |
| - |
75 | 76 | function getAge(otherDateYear, otherDateMonth, otherDateDay) {
|
76 |
| - var otherDate = new Date(), |
77 |
| - nowDate = new Date(); |
78 |
| - otherDate.setYear(otherDateYear); |
79 |
| - otherDate.setMonth(otherDateMonth); |
80 |
| - otherDate.setDate(otherDateDay); |
81 |
| - return new Date(nowDate.getTime() - otherDate.getTime()).getUTCFullYear() - 1970; |
| 77 | + var birthDate = new Date(otherDateYear, otherDateMonth, otherDateDay), now = new Date(), |
| 78 | + years = now.getFullYear() - birthDate.getFullYear(); |
| 79 | + birthDate.setFullYear(birthDate.getFullYear() + years); |
| 80 | + if (birthDate > now) { |
| 81 | + years--; |
| 82 | + birthDate.setFullYear(birthDate.getFullYear() - 1); |
| 83 | + } |
| 84 | + var days = Math.floor((now.getTime() - birthDate.getTime()) / (3600 * 24 * 1000)), |
| 85 | + yearsOld = years + days / (isLeapYear(now.getFullYear()) ? 366 : 365), |
| 86 | + decimals = ((yearsOld + '').split('.')[1] || '').substr(0, 3); |
| 87 | + |
| 88 | + if (yearsOld >= 0) { |
| 89 | + return Math.floor(yearsOld) + (decimals >= 915 ? 1:0); |
| 90 | + } else { |
| 91 | + decimals *= 10; |
| 92 | + return Math.floor(yearsOld) + (decimals <= 840 ? 1:0); |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + function isLeapYear(year) { |
| 97 | + var d = new Date(year, 1, 28); |
| 98 | + d.setDate(d.getDate() + 1); |
| 99 | + return d.getMonth() === 1; |
82 | 100 | }
|
83 | 101 |
|
84 | 102 | })(jQuery);
|
0 commit comments