I am trying to exclude weekends in my JavaScript code. I use moment.js and having difficulty choosing the right variable for 'days'.
So far I have thought that I need to exclude day 6 (saturday) and day 0 (sunday) by changing the weekday variable to count from day 1 to day 5 only. But not sure how it changes.
My jsfiddle is shown here: FIDDLE
HTML:
<div id="myContent">
<input type="radio" value="types" class="syncTypes" name="syncTypes"> <td><label for="xshipping.xshipping1">Free Shipping: (<span id="fsv1" value="5">5</span> to <span id="fsv2" value="10">10</span> working days)</label> </td><br>
<div id="contacts" style="display:none;border:1px #666 solid;padding:3px;top:15px;position:relative;margin-bottom:25px;">
Contacts
</div>
<input type="radio" value="groups" class="syncTypes" name="syncTypes"> <td><label for="xshipping.xshipping2">Express Shipping: (<span id="esv1" value="3">3</span> to <span id="esv2" value="4">4</span> working days)</label> </td>
<div id="groups" style="display:none;border:1px #666 solid;padding:3px;top:15px;position:relative">
Groups
</div>
</div>
JavaScript:
var a = 5; //Free shipping between a
var b = 10;//and b
var c = 3;//Express shipping between c
var d = 4;//and d
var now = moment();
var f = "Your item will be delivered between " + now.add("days",a).format("Do MMMM") + " and " + now.add("days",b).format("Do MMMM");
var g = "Your item will be delivered between " + now.add("days".c).format("Do MMMM") + " and " + now.add("days",d).format("Do MMMM");
var h = document.getElementById('contacts');
h.innerHTML = g
var i = document.getElementById('groups');
i.innerHTML = f
$(function() {
$types = $('.syncTypes');
$contacts = $('#contacts');
$groups = $('#groups');
$types.change(function() {
$this = $(this).val();
if ($this == "types") {
$groups.slideUp(300);
$contacts.delay(200).slideDown(300);
}
else if ($this == "groups") {
$contacts.slideUp(300);
$groups.delay(200).slideDown(300);
}
});
});
Here you go!
function addWeekdays(date, days) {
date = moment(date); // use a clone
while (days > 0) {
date = date.add(1, 'days');
// decrease "days" only if it's a weekday.
if (date.isoWeekday() !== 6 && date.isoWeekday() !== 7) {
days -= 1;
}
}
return date;
}
You call it like this
var date = addWeekdays(moment(), 5);
I used .isoWeekday instead of .weekday because it doesn't depend on the locale (.weekday(0) can be either Monday or Sunday).
Don't subtract weekdays, i.e addWeekdays(moment(), -3) otherwise this simple function will loop forever!
Updated JSFiddle http://jsfiddle.net/Xt2e6/39/ (using different momentjs cdn)
Those iteration looped solutions would not fit my needs.
They were too slow for large numbers.
So I made my own version:
https://github.com/leonardosantos/momentjs-business
Hope you find it useful.
https://github.com/andruhon/moment-weekday-calc plugin for momentJS might be helpful for similar tasks
It does not solves the exact problem, but it is able to calculate specific weekdays in the range.
Usage:
moment().isoWeekdayCalc({
rangeStart: '1 Apr 2015',
rangeEnd: '31 Mar 2016',
weekdays: [1,2,3,4,5], //weekdays Mon to Fri
exclusions: ['6 Apr 2015','7 Apr 2015'] //public holidays
}) //returns 260 (260 workdays excluding two public holidays)
If you want a pure JavaScript version (not relying on Moment.js) try this...
function addWeekdays(date, days) {
date.setDate(date.getDate());
var counter = 0;
if(days > 0 ){
while (counter < days) {
date.setDate(date.getDate() + 1 ); // Add a day to get the date tomorrow
var check = date.getDay(); // turns the date into a number (0 to 6)
if (check == 0 || check == 6) {
// Do nothing it's the weekend (0=Sun & 6=Sat)
}
else{
counter++; // It's a weekday so increase the counter
}
}
}
return date;
}
You call it like this...
var date = addWeekdays(new Date(), 3);
This function checks each next day to see if it falls on a Saturday (day 6) or Sunday (day 0). If true, the counter is not increased yet the date is increased.
This script is fine for small date increments like a month or less.
I would suggest adding a function to the moment prototype.
Something like this maybe? (untested)
nextWeekday : function () {
var day = this.clone(this);
day = day.add('days', 1);
while(day.weekday() == 0 || day.weekday() == 6){
day = day.add("days", 1);
}
return day;
},
nthWeekday : function (n) {
var day = this.clone(this);
for (var i=0;i<n;i++) {
day = day.nextWeekday();
}
return day;
},
And when you're done and written some tests, send in a pull request for bonus points.
d1 and d2 are moment dates passed as an argument to calculateBusinessDays
calculateBusinessDays(d1, d2) {
const days = d2.diff(d1, "days") + 1;
let newDay: any = d1.toDate(),
workingDays: number = 0,
sundays: number = 0,
saturdays: number = 0;
for (let i = 0; i < days; i++) {
const day = newDay.getDay();
newDay = d1.add(1, "days").toDate();
const isWeekend = ((day % 6) === 0);
if (!isWeekend) {
workingDays++;
}
else {
if (day === 6) saturdays++;
if (day === 0) sundays++;
}
}
console.log("Total Days:", days, "workingDays", workingDays, "saturdays", saturdays, "sundays", sundays);
return workingDays;
}
If you want a version of #acorio's code sample which is performant (using #Isantos's optimisation) and can deal with negative numbers use this:
moment.fn.addWorkdays = function (days) {
// Getting negative / positive increment
var increment = days / Math.abs(days);
// Looping weeks for each full 5 workdays
var date = this.clone().add(Math.floor(Math.abs(days) / 5) * 7 * increment, 'days');
// Account for starting on Saturdays and Sundays
if(date.isoWeekday() === 6) { date.add(-increment, 'days'); }
else if(date.isoWeekday() === 7) { date.add(-2 * increment, 'days'); }
// Adding / removing remaining days in a short loop, jumping over weekends
var remaining = days % 5;
while(remaining != 0) {
date.add(increment, 'days');
if(date.isoWeekday() !== 6 && date.isoWeekday() !== 7)
remaining -= increment;
}
return date;
};
See Fiddle here: http://jsfiddle.net/dain/5xrr79h0/
Edit: now fixed issue adding 5 days to a day initially on a weekend
I know this question was posted long ago, but in case somebody bump on this, here is optimized solution using moment.js:
function getBusinessDays(startDate, endDate){
var startDateMoment = moment(startDate);
var endDateMoment = moment(endDate)
var days = Math.round(startDateMoment.diff(endDateMoment, 'days') - startDateMoment .diff(endDateMoment, 'days') / 7 * 2);
if (endDateMoment.day() === 6) {
days--;
}
if (startDateMoment.day() === 7) {
days--;
}
return days;
}
const calcBusinessDays = (d1, d2) => {
// Calc all days used including last day ( the +1 )
const days = d2.diff(d1, 'days') + 1;
console.log('Days:', days);
// how many full weekends occured in this time span
const weekends = Math.floor( days / 7 );
console.log('Full Weekends:', weekends);
// Subtract all the weekend days
let businessDays = days - ( weekends * 2);
// Special case for weeks less than 7
if( weekends === 0 ){
const cur = d1.clone();
for( let i =0; i < days; i++ ){
if( cur.day() === 0 || cur.day() === 6 ){
businessDays--;
}
cur.add(1, 'days')
}
} else {
// If the last day is a saturday we need to account for it
if (d2.day() === 6 ) {
console.log('Extra weekend day (Saturday)');
businessDays--;
}
// If the first day is a sunday we need to account for it
if (d1.day() === 0) {
console.log('Extra weekend day (Sunday)');
businessDays--;
}
}
console.log('Business days:', businessDays);
return businessDays;
}
This can be done without looping between all dates in between.
// get nb of weekend days
var startDateMonday = startDate.clone().startOf('isoWeek');
var endDateMonday = endDate.clone().startOf('isoWeek');
var nbWeekEndDays = 2 * endDateMonday.diff(startDateMonday, 'days') / 7;
var isoDayStart = startDate.isoWeekday();
if (isoDayStart > 5) // starts during the weekend
{
nbWeekEndDays -= (8 - isoDayStart);
}
var isoDayEnd = endDate.isoWeekday();
if (isoDayEnd > 5) // ends during the weekend
{
nbWeekEndDays += (8 - isoDayEnd);
}
// if we want to also exlcude holidays
var startOfStartDate = startDate.clone().startOf('day');
var nbHolidays = holidays.filter(h => {
return h.isSameOrAfter(startOfStartDate) && h.isSameOrBefore(endDate);
}).length;
var duration = moment.duration(endDate.diff(startDate));
duration = duration.subtract({ days: nbWeekEndDays + nbHolidays });
var nbWorkingDays = Math.floor(duration.asDays()); // get only nb of complete days
I am iterating from start date to end date and only counting days which are weekdays.
const calculateBusinessDays = (start_date, end_date) => {
const d1 = start_date.clone();
let num_days = 0;
while(end_date.diff(d1.add(1, 'days')) > 0) {
if ([0, 6].includes(d1.day())) {
// Don't count the days
} else {
num_days++;
}
}
return num_days;
}
Related
This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed last month.
I am new to javascript.
I have specific month columns (9/30/2022, 10/31/2022,11/30/2022). I have a contract with a start date and end date (spanning multiple months).
I need to determine the number of days the contract was active for a specific month column.
Example:
Contact Start Date: 09/15/2022
Contract End Date: 10/24/2022
Number of days the contract was active in Sept 2022 is 16.
I found the code below that gives me the contract period broken down for each month (i.e.) **9 - 17; 10 - 23; **
Thank you in advance for any assistance.
I found this code
function getDays() {
var dropdt = new Date(document.getElementById("arr").value);
var pickdt = new Date(document.getElementById("dep").value);
var result = "";
for (var year = dropdt.getFullYear(); year <= pickdt.getFullYear(); year++) {
var firstMonth = (year == dropdt.getFullYear()) ? dropdt.getMonth() : 0;
var lastMonth = (year == pickdt.getFullYear()) ? pickdt.getMonth() : 11;
for (var month = firstMonth; month <= lastMonth; month++) {
var firstDay = (year === dropdt.getFullYear() && month === firstMonth) ? dropdt.getDate() : 1;
var lastDay = (year === pickdt.getFullYear() && month === lastMonth) ? pickdt.getDate() : 0;
var lastDateMonth = (lastDay === 0) ? (month + 1) : month
var firstDate = new Date(year, month, firstDay);
var lastDate = new Date(year, lastDateMonth, lastDay);
result += (month + 1) + " - " + parseInt((lastDate - firstDate) / (24 * 3600 * 1000) + 1) + "; ";
}
}
return result;
}
function cal() {
if (document.getElementById("dep")) {
document.getElementById("number-of-dates").value = getDays();
}
Calculate
`
The following snippet will generate an object res with the keys being zero-based month-indexes ("8" is for September, "9" for October, etc.) and the values are the number of days for each of these months:
const start=new Date("2022-09-15");
const end=new Date("2022-11-24");
let nextFirst=new Date(start.getTime()), month, days={};
do {
month=nextFirst.getMonth();
nextFirst.setMonth(month+1);nextFirst.setDate(1);
days[month]=Math.round(((nextFirst<end?nextFirst:end)-start)/86400000);
start.setTime(nextFirst.getTime());
} while(nextFirst<end)
console.log(days);
This can be extended into a more reliable function returning a year-month combination:
function daysPerMonth(start,end){
let nextFirst=new Date(start.getTime()), year, month, days={};
do {
year=nextFirst.getFullYear();
month=nextFirst.getMonth();
nextFirst.setMonth(month+1);nextFirst.setDate(1);
days[`${year}-${String(1+month).padStart(2,"0")}`]=Math.round(((nextFirst<end?nextFirst:end)-start)/86400000);
start.setTime(nextFirst.getTime());
} while(nextFirst<end)
return days;
}
[["2022-09-15","2022-11-24"],["2022-11-29","2023-02-04"]].forEach(([a,b])=>
console.log(daysPerMonth(new Date(a),new Date(b))));
Managing and calculating dates, times, and date-times are notoriously finicky in javascript and across browsers. Rather than trying to define your own logic for this use the famous Moment.js library.
In particular to calculate the length between two dates you can utilize the diff function between two moments
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 25]);
var diff = a.diff(b, 'days') // 1
console.log(diff);
<script src="https://momentjs.com/downloads/moment.js"></script>
The supported measurements are years, months, weeks, days, hours, minutes, and seconds.
In a JavaScript step in Pentaho Data Integration, I want calculate the time in hours which passes between one date and another.
After following along with this this blog post, I realize that I need to adjust the startDate and endDate values in the function below which fall outside business hours so that they're within business hours so the function doesn't return zero. The dates are in the format 09/27/2018 18:54:55.
Here's my attempt so far:
var Approve_Gap;
var created_at_copy;
var approved_at_copy1;
// Function that accepts two parameters and calculates
// the number of hours worked within that range
function workingHoursBetweenDates(startDate, endDate) {
// Store minutes worked
var minutesWorked = 0;
// Validate input
if (endDate < startDate) { return 0; }
// Loop from your Start to End dates (by hour)
var current = startDate;
// Define work range
var workHoursStart = 8;
var workHoursEnd = 17;
var includeWeekends = true;
// bring dates into business hours
if(current.getHours() > workHoursEnd) {
current = current - (current.getHours() - workHoursEnd);
}
else if(current.getHours() < workHoursStart) {
current = current + (workHoursStart - current.getHours())
}
if(endDate.getHours() > workHoursEnd) {
endDate = endDate - (endDate.getHours() - workHoursEnd);
}
else if(endDate.getHours() < workHoursStart) {
endDate = endDate + (workHoursStart - endDate.getHours())
}
// Loop while currentDate is less than end Date (by minutes)
while(current <= endDate){
// Is the current time within a work day (and if it
// occurs on a weekend or not)
if(current.getHours() >= workHoursStart && current.getHours() < workHoursEnd && (includeWeekends ? current.getDay() !== 0 && current.getDay() !== 6 : true)){
minutesWorked++;
}
// Increment current time
current.setTime(current.getTime() + 1000 * 60);
}
// Return the number of hours
return minutesWorked / 60;
}
Approve_Gap = workingHoursBetweenDates(created_at_copy, approved_at_copy1);
I got the dates into business hours by adjusting copies of the dates as shown below:
if(created_at_copy.getHours() >= workHoursEnd) {
created_at_copy.setDate(created_at_copy.getDate() + 1);
created_at_copy.setHours(8);
created_at_copy.setMinutes(0);
created_at_copy.setSeconds(0);
} else if(created_at_copy.getHours() < workHoursStart) {
created_at_copy.setHours(8);
created_at_copy.setMinutes(0);
created_at_copy.setSeconds(0);
}
if(approved_at_copy1.getHours() >= (workHoursEnd)) {
approved_at_copy1.setDate(approved_at_copy1.getDate() + 1);
approved_at_copy1.setHours(8);
approved_at_copy1.setMinutes(0);
created_at_copy.setSeconds(0);
} else if(approved_at_copy1.getHours() < workHoursStart) {
approved_at_copy1.setHours(8);
approved_at_copy1.setMinutes(0);
created_at_copy.setSeconds(0);
}
I am trying to write a code where total days will be counted excluding weekends and custom defined holiday. I searched through stackoverflow and adobe forum to find a solution and came with below code.
If public holiday falls in a working day (Saturday-Wednesday) it is excluding from calculation.
My problem is that if public holiday falls in weekend (Thursday-Friday), it is deducting for both (holiday & weekend). Suppose leave duration is 18/09/2018-22/09/2018, total count 2 days is showing in place of 3. Again for 17/10/2018-21/10/2018, total count 1 day is showing in place of 3 days.
Any help or any idea to solve the problem would be great!
Regards
//Thursday and Friday will be excluded as weekend.
var start = this.getField("From").value;
// get the start date value
var end = this.getField("To").value;
var end = util.scand("dd/mm/yyyy H:MM:SS", end + " 0:00:00");
var start =util.scand("dd/mm/yyyy H:MM:SS", start + " 0:00:00");
event.value = dateDifference(start, end);
function dateDifference(start, end) {
// Copy date objects so don't modify originals
var s = new Date(+start);
var e = new Date(+end);
// Set time to midday to avoid daylight saving and browser quirks
s.setHours(12,0,0,0);
e.setHours(12,0,0,0);
// Get the difference in whole days
var totalDays = Math.round((e - s) / 8.64e7);
// Get the difference in whole weeks
var wholeWeeks = totalDays / 7 | 0;
// Estimate business days as number of whole weeks * 5
var days = wholeWeeks * 5;
// If not even number of weeks, calc remaining weekend days
if (totalDays % 7) {
s.setDate(s.getDate() + wholeWeeks * 7);
while (s < e) {
s.setDate(s.getDate() + 1);
// If day isn't a Thursday or Friday, add to business days
if (s.getDay() != 4 && s.getDay() != 5) {
++days;
}
}
}
var hdayar = ["2018/02/21","2018/03/17","2018/03/26","2018/04/14","2018/05/01","2018/08/15","2018/09/2 1","2018/10/18","2018/10/19","2018/12/16","2018/12/25"];
//test for public holidays
var phdays = 0;
for (var i = 0; i <hdayar.length; i++){
if ((Date.parse(hdayar[i]) >= Date.parse(start)) && (Date.parse(hdayar[i]) <= Date.parse(end))) {phdays ++;}}
return days-phdays + 1;
}
You should use a library for this rather than reinventing the wheel.
But if you want to do it yourself you could use .getDay to check if the public holidays are on a weekend.
var weekend = [4, 5], // for Thursday, Friday
holDate, holDay;
for (var i = 0; i < hdayar.length; i++){
holDate = Date.parse(hdayar[i]);
holDay = new Date(holDate).getDay()
if (weekend.indexOf(holDay) == -1 && holDate >= Date.parse(start) && holDate <= Date.parse(end)) {
phdays ++;
}
}
phdays will now contain the number of non-weekend public holidays within the range.
Just have the same requirement and this is the my work around.Hope it helps other
var holiday = ["4/18/2019", "4/19/2019", "4/20/2019", "4/25/2019", "4/26/2019"];
var startDate = new Date();
var endDate = new Date(startDate.setDate(startDate.getDate() + 1));
for (i = 0; i < holiday.length; i++) {
var date = endDate.getDate();
var month = endDate.getMonth() + 1; //Months are zero based
var year = endDate.getFullYear();
if ((month + '/' + date + '/' + year) === (holiday[i])) {
endDate = new Date(endDate.setDate(endDate.getDate() + 1));
if (endDate.getDay() == 6) {
endDate = new Date(endDate.setDate(endDate.getDate() + 2));
} else if (endDate.getDay() == 0) {
endDate = new Date(endDate.setDate(endDate.getDate() + 1));
}
}
}
Here, end date gives you next working day.Here,I'm ignoring current day and start comparing from Next day whether it's holiday or weekend.You can customize dateTime as per your requirement (month + '/' + date + '/' + year).Careful whenever you compares two dates with each other. Because it looks same but actually it's not.So customize accordingly.
How would you increase a a number on a webpage twice a week on specific days and times?
For example the webpage would read:
"2 Apples"
However every Tuesday & Thursday at 9:00pm the number should increase by two.
So by Friday the number should have increased to 6 "Apples"
What's a simple way to increment this in Javascript, php or Jquery?
As it was mentionned in the comments, I advise you to use a cron to handle this.
First, you have to store your value somewhere (file, databse, ...). Then, you should create a cron job, that runs a code that increase and update your value at the given days of the week.
Some help about crons : https://en.wikipedia.org/wiki/Cron#Examples
I would add this post about cron and php : Executing a PHP script with a CRON Job
Hope it helps
Here a Javascript version, you can pass it the date it should start counting, the date you want to know the ammount of apples of, the days of the week apples will be added, the hours of the day the updat will take place and the ammount of apples that will be added on each of these dates.
Date.prototype.addDays = function (days) {
var result = new Date(this);
result.setDate(result.getDate() + days);
return result;
}
Date.prototype.addHours = function (hours) {
var result = new Date(this);
result.setHours(result.getHours() + hours);
return result;
}
function getApples(startdate, date, updateDays, updateTime, applesPerUpdate) {
var startDay = startdate.getDay();
var firstUpdateDate;
for(day of updateDays) {
if (day >= startDay) {//assumes startdate has no time added
firstUpdateDate = startdate.addDays(day - startDay).addHours(updateTime);
break;
}
}
if (!firstUpdateDate)
firstUpdateDate = startdate.addDays(7 - (startDay - updateDays[0])).addHours(updateTime);
var updateDaysReverse = updateDays.slice(0).reverse();//clones the array
var dateDay = date.getDay();
var lastUpdateDate;
for(day of updateDaysReverse) {
if (day < dateDay || day == dateDay && date.getHours() > updateTime) {
lastUpdateDate = date.addDays(day - dateDay);
break;
}
}
if (!lastUpdateDate)
lastUpdateDate = date.addDays(updateDaysReverse[0] - (7 + dateDay));
lastUpdateDate = new Date(Date.UTC(1900 + lastUpdateDate.getYear(), lastUpdateDate.getMonth(), lastUpdateDate.getDate(), updateTime, 0, 0, 0));
var secs = Math.trunc((lastUpdateDate - firstUpdateDate));
if (secs < 0) return 0;
var dayDiffs = [];
for(day of updateDays)
dayDiffs.push(day - updateDays[0]);
var weeks = Math.trunc(secs / 604800000);
var days = Math.trunc((secs % 604800000) / 86400000);
var apples = weeks * updateDays.length;
for(diff of dayDiffs)
{
if (diff <= days)
apples++;
else
break;
}
return apples * applesPerUpdate;
}
// important, day and month is zero-based
var startDate = new Date(Date.UTC(2016, 01, 07, 0, 0, 0, 0));
var updateDays = [2, 4];// 0 = sunday , have to be in order and must be 0 <= x < 7
var updateTime = 9;
console.log(getApples(startDate, new Date(), updateDays, updateTime, 2));
Was more coplicated than I thaught, and i havn't testet it much, so there may be bugs.
Here is a plunker to play with the values.
Wondering if anyone has a solution for checking if a weekend exist between two dates and its range.
var date1 = 'Apr 10, 2014';
var date2 = 'Apr 14, 2014';
funck isWeekend(date1,date2){
//do function
return isWeekend;
}
Thank you in advance.
EDIT Adding what I've got so far. Check the two days.
function isWeekend(date1,date2){
//do function
if(date1.getDay() == 6 || date1.getDay() == 0){
return isWeekend;
console.log("weekend")
}
if(date2.getDay() == 6 || date2.getDay() == 0){
return isWeekend;
console.log("weekend")
}
}
Easiest would be to just iterate over the dates and return if any of the days are 6 (Saturday) or 0 (Sunday)
Demo: http://jsfiddle.net/abhitalks/xtD5V/1/
Code:
function isWeekend(date1, date2) {
var d1 = new Date(date1),
d2 = new Date(date2),
isWeekend = false;
while (d1 < d2) {
var day = d1.getDay();
isWeekend = (day === 6) || (day === 0);
if (isWeekend) { return true; } // return immediately if weekend found
d1.setDate(d1.getDate() + 1);
}
return false;
}
If you want to check if the whole weekend exists between the two dates, then change the code slightly:
Demo 2: http://jsfiddle.net/abhitalks/xtD5V/2/
Code:
function isFullWeekend(date1, date2) {
var d1 = new Date(date1),
d2 = new Date(date2);
while (d1 < d2) {
var day = d1.getDay();
if ((day === 6) || (day === 0)) {
var nextDate = d1; // if one weekend is found, check the next date
nextDate.setDate(d1.getDate() + 1); // set the next date
var nextDay = nextDate.getDay(); // get the next day
if ((nextDay === 6) || (nextDay === 0)) {
return true; // if next day is also a weekend, return true
}
}
d1.setDate(d1.getDate() + 1);
}
return false;
}
You are only checking if the first or second date is a weekend day.
Loop from the first to the second date, returning true only if one of the days in between falls on a weekend-day:
function isWeekend(date1,date2){
var date1 = new Date(date1), date2 = new Date(date2);
//Your second code snippet implies that you are passing date objects
//to the function, which differs from the first. If it's the second,
//just miss out creating new date objects.
while(date1 < date2){
var dayNo = date1.getDay();
date1.setDate(date1.getDate()+1)
if(!dayNo || dayNo == 6){
return true;
}
}
}
JSFiddle
Here's what I'd suggest to test if a weekend day falls within the range of two dates (which I think is what you were asking):
function containsWeekend(d1, d2)
{
// note: I'm assuming d2 is later than d1 and that both d1 and d2 are actually dates
// you might want to add code to check those conditions
var interval = (d2 - d1) / (1000 * 60 * 60 * 24); // convert to days
if (interval > 5) {
return true; // must contain a weekend day
}
var day1 = d1.getDay();
var day2 = d2.getDay();
return !(day1 > 0 && day2 < 6 && day2 > day1);
}
fiddle
If you need to check if a whole weekend exists within the range, then it's only slightly more complicated.
It doesn't really make sense to pass in two dates, especially when they are 4 days apart. Here is one that only uses one day which makes much more sense IMHO:
var date1 = 'Apr 10, 2014';
function isWeekend(date1){
var aDate1 = new Date(date1);
var dayOfWeek = aDate1.getDay();
return ((dayOfWeek == 0) || (dayOfWeek == 6));
}
I guess this is the one what #MattBurland sugested for doing it without a loop
function isWeekend(start,end){
start = new Date(start);
if (start.getDay() == 0 || start.getDay() == 6) return true;
end = new Date(end);
var day_diff = (end - start) / (1000 * 60 * 60 * 24);
var end_day = start.getDay() + day_diff;
if (end_day > 5) return true;
return false;
}
FIDDLE
Whithout loops, considering "sunday" first day of week (0):
Check the first date day of week, if is weekend day return true.
SUM "day of the week" of the first day of the range and the number of days in the lap.
If sum>5 return true
Use Date.getDay() to tell if it is a weekend.
if(tempDate.getDay()==6 || tempDate.getDay()==0)
Check this working sample:
http://jsfiddle.net/danyu/EKP6H/2/
This will list out all weekends in date span.
Modify it to adapt to requirements.
Good luck.