คำนวณอายุ แบบไทย (ปี พศ)
function calcAge(date, month, year) {
month = month - 1;
year = year - 543;
today = new Date();
dateStr = today.getDate();
monthStr = today.getMonth();
yearStr = today.getFullYear();
theYear = yearStr - year;
theMonth = monthStr - month;
theDate = dateStr - date;
var days = "";
if (monthStr == 0 || monthStr == 2 || monthStr == 4 || monthStr == 6 || monthStr == 7 || monthStr == 9 || monthStr == 11) days = 31;
if (monthStr == 3 || monthStr == 5 || monthStr == 8 || monthStr == 10) days = 30;
if (monthStr == 1) days = 28;
inYears = theYear;
if (month < monthStr && date > dateStr) {
inYears = parseInt(inYears) + 1;
inMonths = theMonth - 1;
};
if (month < monthStr && date <= dateStr) {
inMonths = theMonth;
} else if (month == monthStr && (date < dateStr || date == dateStr)) {
inMonths = 0;
} else if (month == monthStr && date > dateStr) {
inMonths = 11;
} else if (month > monthStr && date <= dateStr) {
inYears = inYears - 1;
inMonths = ((12 - -(theMonth)) + 1);
} else if (month > monthStr && date > dateStr) {
inMonths = ((12 - -(theMonth)));
};
if (date < dateStr) {
inDays = theDate;
} else if (date == dateStr) {
inDays = 0;
} else {
inYears = inYears - 1;
inDays = days - (-(theDate));
};
var result = ['day', 'month', 'year'];
result.day = inDays;
result.month = inMonths;
result.year = inYears;
return result;
};
ตัวอย่าง
var age = calcAge(5, 5, 2552);
alert('อายุ ' + age.year + ' ปี ' + age.month + ' เดือน ' + age.day + ' วัน');