使用Javascript获得工作日 [英] Getting Working Days Using Javascript

查看:97
本文介绍了使用Javascript获得工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图在两个约会之间得到工作日。
示例:stdate = 28/10/2011 and endate = 04/11/2011。这应该是6个工作日,但它只给出5天。

I'm trying to get the working days between two date. Example: stdate = 28/10/2011 and endate = 04/11/2011. This should be 6 working days, but its only giving 5 days.

var workingdays = 0;
var weekday     = new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

while (stdate <= endate) 
{
    var day = weekday[stdate.getDay()];
    if(day != "Saturday" && day != "Sunday") 
    {
        workingdays++; 
    }
    console.log(weekday[stdate.getDay()]);
    stdate = new Date(stdate.getTime() + 86400000); 
}

控制台日志显示以下结果。

The console log shows the results below.

Friday
Saturday
Sunday
Sunday
Monday
Tuesday
Wednesday
Thursday

星期日由于某种原因显示两次。任何帮助将不胜感激。

Sunday shows twice for some reason. Any help would be appreciated.

推荐答案

夏令时。

由于你要在24小时内添加日期,因此仅限于星期天的第二天是不够的,因为特定的星期日有25个小时。

As you are adding 24 hours to the date, it's not enough to get you to the next day on the sunday, as that particular sunday has 25 hours.

你应该添加一天而不是添加小时:

You should add a day instead of adding hours:

stdate = new Date(stdate.getFullYear(), stdate.getMonth(), stdate.getDate() + 1);

说明:当你调用 Date 构造函数时如果日期超出范围,它将自动换行到下个月,即新日期(2010,9,32)为您提供11月的第一个。

Explanation: When you call the Date constructor with a date that is out of range, it will automaticall wrap to the next month, i.e. new Date(2010,9,32) gives you the first of November.

这篇关于使用Javascript获得工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆