Home > Net >  show remaining time left after user input
show remaining time left after user input

Time:08-24

I am trying to show the remaining time left after the user inputs their answer.

so it's suppose to be like this. When does that course start? 2022-09-05 (user input) Today it is 32 days left until the course starts

I dont think its suppose to be that complicated but I cant make it work, I keep getting NaN or that it just isnt working.

I have checked MDN but I just dont get it.

The code looks like this.

    function start(timePassedIn) {
      return `Today it is ${timePassedIn} days left until the 
      course starts`;
    }

    const course = prompt("When does that course start? ");
    const starting = start(course);

  
    console.log(starting);

I removed all my attempts at the date so that you can give me fresh input.

Appreciate all the help I can get.

CodePudding user response:

Can you try this.

function start(timePassedIn) {
      return `Today it is ${timePassedIn} days left until the 
      course starts`;
 }
 function getDateDifference(inputDate) {
    const date1 = new Date(inputDate);
    const date2 = new Date();
    const diffTime = Math.abs(date1 - date2);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
  return diffDays;
 }
 const course = prompt("When does that course start? ");
 const starting = start(getDateDifference(course));

CodePudding user response:

dates can be stored in two ways in a program:

  • as a String, for example "October 10th" or "2022-08-01" or "09/11"
  • as Date Objects. You already found the documentation for Date in MDN.

we use Strings for input and output, and Date Objects for computation like the difference between two dates.

If I understand you correclty, your program should

  1. ask the user when the course starts
  2. compute how many days are left until the course starts
  3. output the number of days

When you try to program this step 2 is the complicated one:

1. ask the user when the course starts:

`const course = prompt("When does that course start? ");`

course will contain a string with the date. maybe you would be better off to ask for day and month seperatly?

const month = prompt("When does that course start? Please enter the month as a number");
const day = prompt("When does that course start? Please enter the day as a number");

2. compute how many days are left until the course starts

a) convert the input into a Date object. b) get a date object of the current date c) compute the difference and convert to days

  • Related