如何判斷 JavaScript 中的日期是否是週末?


我們知道星期日的值為 0,星期六的值為 6。首先,你需要藉助 getDay() 獲取日期。

設定一個日期 −

var givenDate=new Date("2020-07-18");

現在,我們將獲取日期 −

var currentDay = givenDate.getDay();

以下程式碼判斷日期是否為週末 −

示例程式碼

var givenDate=new Date("2020-07-18");
var currentDay = givenDate.getDay();
var dateIsInWeekend = (currentDay === 6) || (currentDay === 0);
if(dateIsInWeekend==true){
   console.log("The given date "+givenDate+" is a Weekend");
} else {
   console.log("The given date " +givenDate+"is a not a Weekend");
}

要執行上述程式,你需要使用以下命令 −

node fileName.js.

此處,我的檔名是 demo66.js。

輸出

將產生以下輸出 −

PS C:\Users\Amit\JavaScript-code> node demo66.js
The given date Sat Jul 18 2020 05:30:00 GMT+0530 (India Standard Time) is a Weekend

更新日期: 03-Sep-2020

689 次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.