export function calculateAge(dob) { const userDob = dob.split("/"); const birthDate = new Date(userDob[2], userDob[1]-1, userDob[0]); const today = new Date(); const yyyy = today.getFullYear(); let mm = today.getMonth(); let dd = today.getDate(); if (dd < 10) dd = "0" + dd; if (mm < 10) mm = "0" + mm; const formattedTodayDate = new Date(yyyy, mm, dd); let year_difference = formattedTodayDate.getFullYear() - birthDate.getFullYear(); // 2001 - 2000 = 1 let one_or_zero = formattedTodayDate.getMonth() < birthDate.getMonth() || (formattedTodayDate.getMonth() === birthDate.getMonth() && formattedTodayDate.getDate() < birthDate.getDate()) ? 1 : 0; let age = year_difference - one_or_zero; return age; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter