The DateOutput
function calculates the age of a user based on an input date and determines if the user is a minor or an adult. It also provides an alert message with this information.
-
Retrieve the Date Input:
- The function gets the value of the date entered into an input field with the ID
dateInput
. - If no date is entered, it alerts the user to "Please enter a date" and exits.
- The function gets the value of the date entered into an input field with the ID
-
Calculate the Age:
- Converts the input date into a
Date
object (birthdate
). - Retrieves the current date using the
Date
object (today
). - Computes the year difference between the current year and the year of birth.
- Converts the input date into a
-
Adjust for Month and Day:
- Compares the month and day of the current date with the input date to determine if the birthday has occurred in the current year.
- If the birthday has not yet occurred, the calculated age is decremented by 1.
-
Display the Output:
- Alerts the user if they are an adult (
18 years or older
) or a minor (under 18
). - Displays the calculated age in the alert.
- Alerts the user if they are an adult (
- Input:
2003-10-15
- If today's date is
2025-01-13
:- Age: 21 years (birthday has not occurred yet in the current year).
- Output Alert:
You are Adult, and your age is 21
.
- The function ensures accurate age calculation by factoring in month and day differences.
- Requires an HTML input element with the ID
dateInput
.
<input type="date" id="dateInput">
<button onclick="DateOutput()">Submit</button>