Skip to content

Commit

Permalink
completed js in 24_age_calculator
Browse files Browse the repository at this point in the history
  • Loading branch information
nitishkhobragade committed Apr 14, 2024
1 parent 03a5d0e commit e303fcb
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 10 deletions.
41 changes: 31 additions & 10 deletions 24_age_calculator/age.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,53 @@
let cal_btn = document.querySelector(".calculator");
let getDate, dobDate, dobMonth, dobYear;
let year, month, date;

cal_btn.addEventListener('click', () => {
let dob = document.querySelector("#date").value;
getDate = new Date(dob);
dobDate = getDate.getDate();
dobMonth = getDate.getMonth() + 1;
dobYear = getDate.getFullYear();
let getDate = new Date(dob);
let dobDate = getDate.getDate();
let dobMonth = getDate.getMonth() + 1;
let dobYear = getDate.getFullYear();

// You can log the variables here if you want to see them every time the button is clicked
console.log(getDate, dobDate, dobMonth, dobYear);

let currentDate = new Date();
let currDate = currentDate.getDate();
let currYear = currentDate.getFullYear();
let currMonth = currentDate.getMonth();
let currMonth = currentDate.getMonth() + 1;

// Set variables
let setYear = document.querySelector(".set-year");
let setMonth = document.querySelector(".set-month");
let setDate = document.querySelector(".set-day");

// Calculate the age
year = currYear - dobYear;
console.log(year);
if (currMonth >= dobMonth) {
month = currMonth - dobMonth;
if (currDate < dobDate) {
month--;
let daysInLastMonth = new Date(currYear, currMonth - 1, 0).getDate();
date = daysInLastMonth - dobDate + currDate;
} else {
date = currDate - dobDate;
}
} else {
year--;
date = new Date(year, month, 0).getDate() + currDate - dobDate;
let monthsUntilNextBirthday = dobMonth - currMonth;
if (currDate < dobDate) {
monthsUntilNextBirthday--;
let daysInLastMonth = new Date(currYear, currMonth - 1, 0).getDate();
date = daysInLastMonth - dobDate + currDate;
} else {
date = currDate - dobDate;
}
month = 12 - monthsUntilNextBirthday;
}

// Output the age
console.log(year, date, month);
setYear.textContent = year;
setMonth.textContent = month;
setDate.textContent = date;
});

// Now you can access getDate, dobDate, dobMonth, dobYear, year, date, and month outside the event listener function
1 change: 1 addition & 0 deletions 24_age_calculator/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/x-icon" href="https://nitishkhobragade.github.io/js_small_projects/logo-n.png">
<title>Age Calculator | Javascript Project for Beginners</title>
<link rel="stylesheet" href="./age.css">
</head>
Expand Down

0 comments on commit e303fcb

Please sign in to comment.