Home > database >  I've written a simple JS program for Age Calculator
I've written a simple JS program for Age Calculator

Time:01-05

If in the JavaScript, we write program today = new Date("2022 03 01") and we put input "2022 02 28" in the input column, the result comes out as 4 days instead of 1 day. Can someone help me with this one particular case. Also I don't know if what I've written is correct or wrong, can someone help me with this Age Calculator program. I've attached all the HTML, CSS and JS files

function calculateAge() {
  let bdate = document.querySelector("#Isdate").value
  let bmonth = document.querySelector("#Ismonth").value
  let byear = document.querySelector("#Isyear").value

  let validate = validateInput(bdate, bmonth, byear)

  if (validate) {
    let today = new Date()
    let tdate = today.getDate()
    let tmonth = today.getMonth()   1
    let tyear = today.getFullYear()

    // console.log(tyear)
    // let tdate = 01
    // let tmonth = 03
    // let tyear = 2022

    let BirthYear = tyear - byear
    let BirthMonth
    let BirthDate

    if (tmonth >= bmonth) {
      BirthMonth = tmonth - bmonth
    } else {
      BirthMonth = 12 - (bmonth - tmonth)
      BirthYear--
    }

    if (tdate >= bdate) {
      BirthDate = tdate - bdate
    } else {
      BirthMonth--
      BirthDate = 31 - (bdate - tdate)

      // case where a BirthMonth can go negative 
      if (BirthMonth < 0) {
        BirthYear--
        BirthMonth = 11
      }
    }

    if (BirthYear < 0) {
      document.querySelector("#output-result").innerHTML = "Date of birth needs to be earlier than Current date"
    } else {
      document.querySelector("#output-result").innerHTML = `Your Age Is ${BirthYear} Years, ${BirthMonth} Months & ${BirthDate} Days`
    }
  }
}

function validateInput(bdate, bmonth, byear) {

  if (!bdate) {
    document.querySelector("#output-result").innerHTML = "Please provide a date"
    return false;
  }
  if (!bmonth) {
    document.querySelector("#output-result").innerHTML = "Please provide a Month"
    return false;
  }
  if (!byear) {
    document.querySelector("#output-result").innerHTML = "Please provide a Year"
    return false;
  }

  if (parseInt(bmonth) > 12) {
    document.querySelector("#output-result").innerHTML = "Please provide Month value in the range from 1 to 12"
    return false;
  }

  if (byear.length < 4) {
    document.querySelector("#output-result").innerHTML = "Provide year in format YYYY"
    return false;
  }

  if (parseInt(bdate) <= 0) {
    document.querySelector("#output-result").innerHTML = "Date cannot be 0 or less than 0"
    return false;
  }
  if (parseInt(bmonth) <= 0) {
    document.querySelector("#output-result").innerHTML = "Month cannot be 0 or less than 0"
    return false;
  }
  if (parseInt(byear) <= 0) {
    document.querySelector("#output-result").innerHTML = "Year cannot be 0 or less than 0"
    return false;
  }

  if (isNaN(bdate)) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date"
    return false;
  }
  if (isNaN(bmonth)) {
    document.querySelector("#output-result").innerHTML = "Please provide valid month"
    return false;
  }
  if (isNaN(byear)) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Year"
    return false;
  }

  if (parseInt(bdate) > 31 && parseInt(bmonth) == 1) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 28 && parseInt(bmonth) == 2) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 31 && parseInt(bmonth) == 3) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 30 && parseInt(bmonth) == 4) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 31 && parseInt(bmonth) == 5) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 30 && parseInt(bmonth) == 6) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 31 && parseInt(bmonth) == 7) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 31 && parseInt(bmonth) == 8) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 30 && parseInt(bmonth) == 9) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 31 && parseInt(bmonth) == 10) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 30 && parseInt(bmonth) == 11) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 31 && parseInt(bmonth) == 12) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }

  return true;
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  background: linear-gradient(103.71deg, rgba(97, 192, 191, 0.28) 5.64%, rgba(255, 182, 185, 0.46) 45.19%, #FAE3D9 86.43%);
  height: 100vh;
  width: 100%;
  padding-top: 5rem;
}

.container .heading>h1 {
  font-family: 'Sen', sans-serif;
  font-weight: 400;
  font-size: 96px;
  line-height: 115.5px;
  text-align: center;
  text-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25);
  text-transform: capitalize;
}

span {
  font-family: 'Sen', sans-serif;
  font-style: normal;
  font-weight: 400;
  font-size: 36px;
  line-height: 43px;
  text-align: center;
  text-transform: capitalize;
}

input {
  width: 180px;
  height: 43px;
  border: none;
  outline: none;
  box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.25);
  padding: 20px;
  font-size: 20px;
}

.input-info {
  display: flex;
  gap: 125px;
  justify-content: center;
  margin-top: 7rem;
}

.date,
.month,
.year {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 3rem;
}

.submit {
  text-align: center;
  margin-top: 6rem;
}

.submit button {
  width: 275px;
  height: 56px;
  background: rgba(60, 160, 255, 0.84);
  font-family: 'Sen';
  font-style: normal;
  font-weight: 400;
  font-size: 40px;
  color: #FFFFFF;
  border: none;
  outline: none;
  letter-spacing: 0.09em;
  text-transform: capitalize;
  cursor: pointer;
}

.output {
  text-align: center;
  margin-top: 6rem;
  font-family: 'Sen';
  font-style: normal;
  font-weight: 400;
  font-size: 32px;
  color: #20B2AA;
  line-height: 29px;
  text-transform: capitalize;
  letter-spacing: 0.09em;
}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Sen:wght@400;700;800&display=swap" rel="stylesheet">


<section >
  <div >
    <h1>age calculator</h1>
  </div>
  <div >
    <div >
      <span>Date(DD)</span>
      <input type="text" id="Isdate">
    </div>
    <div >
      <span>Month(MM)</span>
      <input type="text" id="Ismonth" name="" id="">
    </div>
    <div >
      <span>Year (YYYY)</span>
      <input type="text" id="Isyear" name="" id="">
    </div>
  </div>
  <div >
    <button type="submit" onclick="calculateAge()">Submit</button>
  </div>
  <div >
    <p id="output-result"></p>
  </div>
</section>

I want you to check whether the code that I've written is correct or wrong. My senior told me that if (tdate >= bdate) { BirthDate = tdate - bdate } else{ BirthMonth-- BirthDate = 31 - (bdate - tdate) this part can be written differently (please help)

CodePudding user response:

The javascript date object contains everything you need without you having to account for months with different days and leap years. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

At the heart of every date object is a numerical value representing the number of milliseconds since January 1, 1970, UTC (and agreed datum).

When you create a data object with a date string, the underlying epoch time string is referenced using the getTime() method of the date object:

today = new Date("2022 03 01");
console.log(today.getTime());

The sure and simple way to calculate the number of days between two date strings is to construct theirDate objects, subtract their underlying epoch times from each other, and divide the resulting milliseconds value by the number of milliseconds in a day:

const today = new Date("2022 03 01");
const birthDate = new Date("2022 02 28");
const milliSecPerDay= 1000*60*60*24;

let elapsedDays = (today-birthDate)/milliSecPerDay;

console.log(`elapsed days = ${elapsedDays}`);

CodePudding user response:

There are several ways to write a routine to calculate age. Some are more elegant than others. I wrote a javascript that I use anytime I need to display an age broken down by years, months, days.

The basic logic is to use math to determine the number of years and months... this is achieved by knowing how many milliseconds (ms) are in a year and month. The code you see here accounts for leap year where each year = 365.25 days

The craziness occurs whenever trying to determine the days because of the different amount of days in each month including leap year has an extra day in february. The idea here is to create a date to substract from and let the javascript determine if there was a leap year and how many days in the month, etc..

calcAge = (nMonth, nDay, nYear) =>{
  let dtBirth = new Date(nYear, nMonth - 1, nDay);
  let dtNow = new Date();
  
  if(dtBirth > dtNow) return "Only a terminator can be born in the future";
  
  let msYear = 31557600000; // milliseconds in a year (365.25 days)
  let msMonth = msYear / 12; // milliseconds in a month
  let msDay = 86400000; // milliseconds in a day
  
  let nYears = Math.floor((dtNow - dtBirth) / msYear);
  let msRemain = (dtNow - dtBirth) % msYear;
  let nMonths = Math.floor(msRemain / msMonth);
  
  // determine if needing to adjust month and/or year
  if(dtBirth.getDate() > dtNow.getDate()){
    if(dtNow.getMonth() == 0){
      dtNow.setMonth(11);
      dtNow.setFullYear(dtNow.getFullYear() - 1);
    }
    else
        dtNow.setMonth(dtNow.getMonth() - 1);
  }  
  dtNow.setDate(dtBirth.getDate());
  
  let nDays = Math.floor((new Date() - dtNow) / msDay);
  
  return `You are ${nYears} ${nYears == 1 ? 'year' : 'years'}, ${nMonths} ${nMonths == 1 ? 'month' : 'months'}, and ${nDays} ${nDays == 1 ? 'day' : 'days'} old`
}

console.log(calcAge(01,08,2011));

  • Related