我有这些日期变量
minVal = new Date(parseInt(dateArr[2]), parseInt(dateArr[0]) - 1, parseInt(dateArr[1]), 00, 00, 00);
maxVal = new Date(parseInt(dateArrTo[2]), parseInt(dateArrTo[0]) - 1, parseInt(dateArrTo[1]), 23, 59, 59);
我用它们来绘制图表。
我需要区分两件事:
- 30 天内的图表。
- 30 天后图表。
因此,我需要知道这些日期之间的差异(以天为单位)
我尝试这样做:
if ((maxVal.getMonth() - minVal.getMonth()) == 0)
它适用于某些值,但不适用于某些值。例如,如果最短日期为 2014 年 1 月 29 日
,最长日期为 2014 年 2 月 1 日
,则不起作用。
我知道这一点,因为我正在计算月份。
但是我不知道如何计算天数
我知道 getDate()
函数可以检索天数,但我真的不知道如何使用它。
感谢您的帮助
最佳答案
试试这个
function workingDaysBetweenDates(startDate, endDate, getWorkingDays) {
startDate = new Date(startDate);
endDate = new Date(endDate);
// Validate input
if (endDate < startDate)
return 0;
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0,0,0,1); // Start just after midnight
endDate.setHours(23,59,59,999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.ceil(diff / millisecondsPerDay);
if(getWorkingDays){
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days = days - (weeks * 2);
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1)
days = days - 2;
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6)
days = days - 1;
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0)
days = days - 1;
}
return days;
}
workingDaysBetweenDates(start_date, end_date, false);
这是工作 fiddle :http://jsfiddle.net/kailashyadav/72b27/
日期格式需要是以下之一:04/24/2014 或 2014-04-24
第三个参数是要获取工作日还是日历天
关于javascript - javascript 如何获取以天为单位的日期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23196031/