-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
79 lines (68 loc) · 2.42 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css"
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Age Calculator</title>
</head>
<body>
<div class="container">
<div class="header">
<img src="images/logo.jpg" width="100px" alt="code alpha logo">
<h2> INTERNSHIP ASSIGNMENT</h2>
</div>
<h2 class="head-text">Calculate your age and know how old you are!</h2>
<div class="main">
<label for="day">Day:</label>
<input type="number" id="day" min="1" max="31">
<label for="month">Month:</label>
<input type="number" id="month" min="1" max="12">
<label for="year">Year:</label>
<input type="number" id="year" min="1900">
<button onclick="calculateAndDisplayAge()">Submit</button>
</div>
<div id="result" class="output"></div>
</div>
<script>
function calculateAndDisplayAge() {
const day = parseInt(document.getElementById("day").value);
const month = parseInt(document.getElementById("month").value) - 1; // Month starts from 0
const year = parseInt(document.getElementById("year").value);
// Check if the input is valid
if (isNaN(day) || isNaN(month) || isNaN(year)) {
alert("Please enter valid values for day, month, and year.");
return;
}
const birthDate = new Date(year, month, day);
const age = calculateAge(birthDate);
const resultDiv = document.getElementById("result");
resultDiv.innerHTML = `You are ${age.years} years, ${age.months} months, and ${age.days} days old.`;
}
function calculateAge(birthDate) {
const today = new Date();
const birth = new Date(birthDate);
let years = today.getFullYear() - birth.getFullYear();
let months = today.getMonth() - birth.getMonth();
let days = today.getDate() - birth.getDate();
// Check if the birth month is after the current month
if (months < 0 || (months === 0 && today.getDate() < birth.getDate())) {
years--;
months = 12 - Math.abs(months);
}
// Adjust months if days are negative
if (days < 0) {
months--;
// Calculate days in the birth month
const tempDate = new Date(today.getFullYear(), today.getMonth(), 0);
days = tempDate.getDate() - birth.getDate() + today.getDate();
}
return {
years: years,
months: months,
days: days
};
}
</script>
</body>
</html>