如何显示月份和当前工作日的总工作日javascript [英] How to display total workdays in month and current workday javascript
问题描述
正在搜索一种解决方案,以显示当前月的总工作日中的当前工作日.在这种情况下,工作日定义为星期一,星期二,星期三,星期四和星期五.
Was searching for a solution to display the current workday over the total workdays in the current month. Workdays in this case are defined as Mon, Tues, Wed, Thurs, & Fri.
Closest solution I found was this: How to find business days in current month with Javascript?
使用帖子的建议答案并稍加修改,我如何对其进行编辑以显示当月的当前工作日和总工作日?
Using this post's suggested answer with a slight edit, how can I edit this to display the current workday and total workdays in the month?
这是我 CodePen 的尝试.
HTML:
<h3>Get workdays in current month with JavaScript</h3>
<p>Current Day: <span id="currentDay"></span></p>
<p>Total Days: <span id="totalDays"></span></p>
JS:
function isWeekday(year, month, day) {
var day = new Date(year, month, day).getDay();
return day !=0 && day !=6;
}
function getWeekdaysInMonth(month, year) {
var days = daysInMonth(month, year);
var weekdays = 0;
for(var i=0; i< days; i++) {
if (isWeekday(year, month, i+1)) weekdays++;
}
$('#totalDays').html(weekdays);
}
推荐答案
这是我的解决方案;应该非常不言自明:
Here's my solution; should be pretty self-explanatory:
const holidays = [
[7, 4], // 4th of July
[10, 31] // Halloween
];
var d = new Date();
var currentDay = d.getDate();
var year = d.getYear() + 1900;
var month = d.getMonth();
var total = 0;
var done = 0;
for (var day = 1; day <= 31; day++) {
var t = new Date(year, month, day);
if (t.getMonth() > month) break; // month has less than 31 days
if (t.getDay() == 0 || t.getDay() == 6) continue; // no weekday
if (holidays.some(h => h[0] - 1 === month && h[1] === day)) continue; // holiday
total++; // increase total
if (t.getDate() <= currentDay) done++; // increase past days
}
document.body.innerHTML = `Today is weekday ${done} of ${total}.`
该循环遍历当月的所有天,并计算所有工作日和过去的工作日.
The loop goes through all days of the current month and counts all weekdays and past weekdays.
添加了(不完整的)假日数组并进行检查
added (incomplete) holiday array and check
这篇关于如何显示月份和当前工作日的总工作日javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!