Skip to content
Advertisement

Calculate date from today and change color of text for like after 7days

I want to write a javascript that will calculate age from submittal date to today and if the item is more than 5days old will change color of text to yellow and red if its more than 10days old.

<p>text<p>
<input type="date" id="date" name="date">
<input type="submit" value="Submit">

Advertisement

Answer

<html>
<body>
 <p>Your Age Calc<p>
 <form method="GET">
   <input type="date" id="date" name="date">
   <button type="button" id="mybutton">Submit</button>
 </form>
 <div id="result"></div>
<script type="application/javascript">

function showResult() {
 let result =  document.getElementById("result")
 let date = document.getElementById("date");
 if (date.value === "" ) {
  result.innerHTML = "Please input a correct date, 😅!";
  } else {
    let birthday = new Date (`${date.value}`)
    let ageDifMs = Date.now() - birthday.getTime();
    let num_days = ((ageDifMs % 31536000000) % 2628000000)/86400000;
    num_days > 10 ? result.style.color = "green" : result.style.color = "blue"
    result.innerHTML = "😆 Your age(days), " + num_days.toFixed(1);
  }
}

document.getElementById("mybutton").onclick = showResult;

</script>
</body>
</html>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement