簡體   English   中英

顯示用戶輸入后剩余的時間

[英]show remaining time left after user input

我試圖顯示用戶輸入答案后剩余的時間。

所以它應該是這樣的。 該課程什么時候開始? 2022-09-05 (用戶輸入)今天距離課程開始還有32

我不認為它應該那么復雜,但我不能讓它工作,我不斷得到 NaN 或者它只是不工作。

我已經檢查過MDN ,但我就是不明白。

代碼看起來像這樣。

    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);

我刪除了我在該日期的所有嘗試,以便您可以給我新的輸入。

感謝我能得到的所有幫助。

你能試試這個。

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));

日期可以在程序中以兩種方式存儲:

  • 作為字符串,例如“October 10th”或“2022-08-01”或“09/11”
  • 作為日期對象。 您已經在 MDN 中找到了 Date的文檔。

我們使用字符串作為輸入,使用 output,使用日期對象計算兩個日期之間的差異。

如果我理解你的正確,你的程序應該

  1. 在課程開始時詢問用戶
  2. 計算距離課程開始還有多少天
  3. output 天數

當您嘗試對此步驟進行編程時,第 2 步很復雜:

1. 課程開始時詢問用戶:

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

course將包含一個帶日期的字符串。 也許您最好分別詢問日期和月份?

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.計算距離課程開始還有多少天

a) 將輸入轉換為日期 object。 b) 獲取當前日期的日期 object c) 計算差異並轉換為天

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM