如何判断 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.