Reputation: 51
HTML CODE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lab 3</title>
</head>
<body>
<form id ="form" action="" method="get" class="countdown">
<div class="countdown">
<label for="birthday">Enter your next birthday: </label>
<input type="date" name="birthday" id="birthday" required>
</div>
<div class="countdown">
<input type="submit" value="Submit"
</div>
</form>
<script src ="moment/moment.min.js"></script>
<script src="lab3.js"></script>
</body>
</html>
JavaScript CODE: I am not able to format the amntOfDays to only output days. I am currently receiving invalid date as an output. I am not sure what's wrong.
window.addEventListener("load", function(){
document.getElementById("form").addEventListener("submit",function(e){
e.preventDefault();
const bDay = document.getElementById("birthday").value;
let amntOfTime = moment(bDay).fromNow();
let amntOfDays = moment(amntOfTime).format('days')
let day = moment(bDay).format('dddd')
let monAndYr = moment(bDay).format("MMMM Do YYYY")
console.log(`There are ${amntOfDays} until your next birthday<br> Your next birthday is ${day} ${monAndYr}.`)
})
})
Upvotes: 0
Views: 1050
Reputation: 16127
You can use .diff
function to get the number of days until the birthday.
The function will return a number, then you have to update your message:
const amntOfDays = moment(bDay).diff(moment(), "day")
Upvotes: 0
Reputation: 19573
It's because you are passing amntOfTime
to moment()
. amntOfTime
is a relative time string, not a date string, so its not something you should pass to moment, ie
moment("2021-02-17").fromNow(); // "in 3 days"
moment("2021-02-17").fromNow(true); // "3 days"
So that should already be in the format you want. Moment automatically infers that you would want this back in days, as opposed to, say, minutes or seconds, so you don't have to convert anything further.
https://momentjs.com/docs/#/displaying/fromnow/
Your code should just be:
let amntOfDays = moment(bDay).fromNow();
Upvotes: 1