用 JavaScript 獲取明天和後天的日期


使用 JavaScript 的 Date 類,其物件 new Date() 返回當前日期的 JavaScript 日期,我們必須找到後兩天的日期。

這是一個很簡單的問題,我們用幾行程式碼就能解決。首先,獲取今天的日期 −

// getting today's date
const today = new Date();

讓我們編寫這個函式的程式碼 −

// getting today's date
const today = new Date();
// initializing tomorrow with today's date
const tomorrow = new Date(today);
// increasing a day in tomorrow and setting it to tomorrow
tomorrow.setDate(tomorrow.getDate() + 1);
const dayAfterTomorrow = new Date(today);
dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 2);
console.log(today);
console.log(tomorrow);
console.log(dayAfterTomorrow);

輸出

以下是在控制檯中的輸出 −

2020-08-13T17:13:26.401Z
2020-08-14T17:13:26.401Z
2020-08-15T17:13:26.401Z

更新於: 14-Sep-2020

680 次瀏覽

啟動 事業

完成課程認證

開始
廣告
© . All rights reserved.