How to find the days of the week in JavaScript - javascript

I am trying to find the weekdays from today to Sunday. Since today is Monday I want to display the dates from Monday till Sunday, but tomorrow, I want my programme works from Tuesday to Sunday.
dateSets() {
let firstDayOfWeek = "";
let dates = [];
firstDayOfWeek = new Date();
let sunday = new Date();
sunday.setDate(sunday.getDate() - sunday.getDay() + 7);
const diff = sunday.getDate() - firstDayOfWeek.getDate();
dates.push(new Date());
for (let i = 0; i < diff; i++) {
dates.push(
new Date(firstDayOfWeek.setDate(firstDayOfWeek.getDate() + 1))
);
}
return dates;
},
And here is the other function to find the date of the week:
getDateOfWeek(week, year) {
let simple = new Date(year, 0, 1 + (week - 1) * 7);
let dow = simple.getDay();
let weekStart = simple;
if (dow <= 4) weekStart.setDate(simple.getDate() - simple.getDay() + 1);
else weekStart.setDate(simple.getDate() + 8 - simple.getDay());
return weekStart;
},
But it doesn't work that I expected, in dataset, only Monday is being displayed but not other dates and I don't understand the reason. If you can help me with this, I would be really glad.
Thanks...

function getWeekDates(){
const dates = [new Date()]; // today
const curr = new Date();
const remDaysCount = 7-curr.getDay();
for(let i=1; i<= remDaysCount; i++){
// increase current Date by 1 and set to current Date
const nextDate = curr.setDate(curr.getDate()+1);
dates.push(new Date(nextDate));
}
return dates;
}
console.log(getWeekDates());

This is kind of your choice but if you install NodeJS and open your folder in cmd and type in 'npm init' and 'npm I days' and open your editor and type in
var days = require('days');
console.log(days); // ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
console will reveal all of the days of the week and if you want a specific day you can do the following
var days = require('days');
console.log(days[0]); //Sunday
if you need help with installing NodeJS watch a YouTube video or reply to this comment I will help

let firstDayOfWeek = "";
let dates = [];
firstDayOfWeek = new Date();
let sunday = new Date();
sunday.setDate(sunday.getDate() - sunday.getDay() + 7);
//const diff = sunday.getDate() - firstDayOfWeek.getDate();
//Try this code
var timeDiff = Math.abs(sunday.getTime() - firstDayOfWeek.getTime());
var diff = Math.ceil(timeDiff / (1000 * 3600 * 24));
dates.push(new Date());
for (let i = 0; i < diff; i++) {
dates.push(
new Date(firstDayOfWeek.setDate(firstDayOfWeek.getDate() + 1))
);
}
return dates;

Your issue is here:
const diff = sunday.getDate() - firstDayOfWeek.getDate()
Currently the date is 27 Sep and next Sunday is 3 Oct so diff is -4 and the for loop test i < diff is false from the start. Consider using a loop and increment the date from today until it gets to Sunday.
function getDaysToSunday(date = new Date()) {
let d = new Date(+date);
let result = [];
do {
result.push(new Date(+d));
d.setDate(d.getDate() + 1);
} while (d.getDay() != 1)
return result;
}
console.log(getDaysToSunday().map(d=>d.toDateString()));

Related

Show next date while skipping holidays in javascript [duplicate]

I have a javascript function which is calculating working days between 2 dates, it works, but the problem is that it not consider holidays. How can I modify this function, for example by adding holidays in exception array?
Searched in internet about this question, but haven't find about holidays exception.
For example holidays array:
var holidays = ['2016-05-03','2016-05-05'];
And I have a functions to calculate this:
function workingDaysBetweenDates(d0, d1) {
var startDate = parseDate(d0);
var endDate = parseDate(d1);
// 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);
// 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;
}
function parseDate(input) {
// Transform date from text to date
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
Have made an example in jsfiddle:
JSFiddle example
Maybe there are some other functions which can easy use in Jquery?
Try:
var startDate = new Date('05/03/2016');
var endDate = new Date('05/10/2016');
var numOfDates = getBusinessDatesCount(startDate,endDate);
function getBusinessDatesCount(startDate, endDate) {
let count = 0;
const curDate = new Date(startDate.getTime());
while (curDate <= endDate) {
const dayOfWeek = curDate.getDay();
if(dayOfWeek !== 0 && dayOfWeek !== 6) count++;
curDate.setDate(curDate.getDate() + 1);
}
alert(count);
return count;
}
The easiest way to achieve it is looking for these days between your begin and end date.
Edit: I added an additional verification to make sure that only working days from holidays array are subtracted.
$(document).ready(() => {
$('#calc').click(() => {
var d1 = $('#d1').val();
var d2 = $('#d2').val();
$('#dif').text(workingDaysBetweenDates(d1,d2));
});
});
let workingDaysBetweenDates = (d0, d1) => {
/* Two working days and an sunday (not working day) */
var holidays = ['2016-05-03', '2016-05-05', '2016-05-07'];
var startDate = parseDate(d0);
var endDate = parseDate(d1);
// 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);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days -= weeks * 2;
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1) {
days -= 2;
}
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6) {
days--;
}
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0) {
days--;
}
/* Here is the code */
holidays.forEach(day => {
if ((day >= d0) && (day <= d1)) {
/* If it is not saturday (6) or sunday (0), substract it */
if ((parseDate(day).getDay() % 6) != 0) {
days--;
}
}
});
return days;
}
function parseDate(input) {
// Transform date from text to date
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="d1" value="2016-05-02"><br>
<input type="text" id="d2" value="2016-05-08">
<p>Working days count: <span id="dif"></span></p>
<button id="calc">Calc</button>
<p>
Now it shows 5 days, but I need for example add holidays
3 and 5 May (2016-05-03 and 2016-05-05) so the result will be 3 working days
</p>
I took a similar approach to #OscarGarcia mainly as an excercise since my JS is rusty.
While it looks similar, it takes care not to substract a day twice if a holiday happens to be on a saturday or sunday. This way, you can pre-load a list of recurring dates (such as Dec 25th, Jan 1st, July 4th, which may or may not be on an otherwise working day -monday thru friday-)
$(document).ready(function(){
$('#calc').click(function(){
var d1 = $('#d1').val();
var d2 = $('#d2').val();
$('#dif').text(workingDaysBetweenDates(d1,d2));
});
});
function workingDaysBetweenDates(d0, d1) {
var startDate = parseDate(d0);
var endDate = parseDate(d1);
// populate the holidays array with all required dates without first taking care of what day of the week they happen
var holidays = ['2018-12-09', '2018-12-10', '2018-12-24', '2018-12-31'];
// Validate input
if (endDate < startDate)
return 0;
var z = 0; // number of days to substract at the very end
for (i = 0; i < holidays.length; i++)
{
var cand = parseDate(holidays[i]);
var candDay = cand.getDay();
if (cand >= startDate && cand <= endDate && candDay != 0 && candDay != 6)
{
// we'll only substract the date if it is between the start or end dates AND it isn't already a saturday or sunday
z++;
}
}
// 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);
// 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
// substract the holiday dates from the original calculation and return to the DOM
return days - z;
}
function parseDate(input) {
// Transform date from text to date
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
2018-12-09 is a sunday... with this code, it'll only be substracted once (for being a sunday) and not twice (as it would if we only checked if its a national holiday)
I think this solution is much more simpler
const numberOfDaysInclusive = (d0, d1) => {
return 1 + Math.round((d1.getTime()-d0.getTime())/(24*3600*1000));
}
const numberOfWeekends = (d0, d1) => {
const days = numberOfDaysInclusive(d0, d1); // total number of days
const sundays = Math.floor((days + (d0.getDay() + 6) % 7) / 7); // number of sundays
return 2*sundays + (d1.getDay()==6) - (d0.getDay()==0); // multiply sundays by 2 to get both sat and sun, +1 if d1 is saturday, -1 if d0 is sunday
}
const numberOfWeekdays = (d0, d1) => {
return numberOfDaysInclusive(d0, d1) - numberOfWeekends(d0, d1);
}
Get all weekdays between two dates:
private getCorrectWeekDays(StartDate,EndDate){
let _weekdays = [0,1,2,3,4];
var wdArr= [];
var currentDate = StartDate;
while (currentDate <= EndDate) {
if ( _weekdays.includes(currentDate.getDay())){
wdArr.push(currentDate);
//if you want to format it to yyyy-mm-dd
//wdArr.push(currentDate.toISOString().split('T')[0]);
}
currentDate.setDate(currentDate.getDate() +1);
}
return wdArr;
}
You can also try this piece of code:
const moment = require('moment-business-days');
/**
*
* #param {String} date - iso Date
* #returns {Number} difference between now and #param date
*/
const calculateDaysLeft = date => {
try {
return moment(date).businessDiff(moment(new Date()))
} catch (err) {
throw new Error(err)
}
}
The top answer actually works but with a flaw.
When the holyday is in a Saturday or Sunday it still reduces a day.
Add this to the existing code:
.... /* Here is the code */
for (var i in holidays) {
if ((holidays[i] >= d0) && (holidays[i] <= d1)) {
// Check if specific holyday is Saturday or Sunday
var yourDate = new Date(holidays[i]);
if(yourDate.getDay() === 6 || yourDate.getDay() === 0){
// If it is.. do nothing
} else {
// if it is not, reduce a day..
days--;
}
}
}
const workday_count = (start, end) => {
start = moment(start).format(("YYYY-MM-DD"))
end = moment(end).format(("YYYY-MM-DD"))
let workday_count = 0;
let totalDays = moment(end).diff(moment(start), "days");
let date = start
for (let i = 1; i <= totalDays; i++) {
if (i == 1) {
date = moment(date)
} else {
date = moment(date).add(1, "d");
}
date = new Date(date);
let dayOfWeek = date.getDay();
let isWeekend = (dayOfWeek === 6) || (dayOfWeek === 0);
if (!isWeekend) {
workday_count = workday_count + 1;
}
}
return workday_count;
}
Simply reduce the length of array from the value you have got (in your fiddle)
var numberofdayswithoutHolidays= 5;
var holidays = ['2016-05-03','2016-05-05'];
alert( numberofdayswithoutHolidays - holidays.length );
You need to filter out weekends from holidays as well
holidays = holidays.filter( function(day){
var day = parseDate( day ).getDay();
return day > 0 && day < 6;
})
$(document).ready(() => {
$('#calc').click(() => {
var d1 = $('#d1').val();
var d2 = $('#d2').val();
$('#dif').text(workingDaysBetweenDates(d1,d2));
});
});
let workingDaysBetweenDates = (d0, d1) => {
/* Two working days and an sunday (not working day) */
var holidays = ['2016-05-03', '2016-05-05', '2016-05-07'];
var startDate = parseDate(d0);
var endDate = parseDate(d1);
// 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);
// Subtract two weekend days for every week in between
var weeks = Math.floor(days / 7);
days -= weeks * 2;
// Handle special cases
var startDay = startDate.getDay();
var endDay = endDate.getDay();
// Remove weekend not previously removed.
if (startDay - endDay > 1) {
days -= 2;
}
// Remove start day if span starts on Sunday but ends before Saturday
if (startDay == 0 && endDay != 6) {
days--;
}
// Remove end day if span ends on Saturday but starts after Sunday
if (endDay == 6 && startDay != 0) {
days--;
}
/* Here is the code */
holidays.forEach(day => {
if ((day >= d0) && (day <= d1)) {
/* If it is not saturday (6) or sunday (0), substract it */
if ((parseDate(day).getDay() % 6) != 0) {
days--;
}
}
});
return days;
}
function parseDate(input) {
// Transform date from text to date
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="d1" value="2016-05-02"><br>
<input type="text" id="d2" value="2016-05-08">
<p>Working days count: <span id="dif"></span></p>
<button id="calc">Calc</button>
<p>
Now it shows 5 days, but I need for example add holidays
3 and 5 May (2016-05-03 and 2016-05-05) so the result will be 3 working days
</p>

Looping through each month between two years

My javascript is horrible, I am a C# dev but here we are. So I need to loop through every month between a start year and month to an end year and month.
The startMonth and startYear will always be 1 and 2010 respectively.
I have the following solution at the moment:
//Get the current year and month
let currentTime = new Date();
let currentYear = currentTime.getFullYear();
let currentMonth = currentTime.getMonth() + 1;
//Set starting year and month
let startYear = 2010;
let startMonth = 1;
//Loop through the years and months
for (let i = startYear; i <= currentYear; i++){
if (i === currentYear ){
for (let k = 1; k <= currentMonth; k++){
//Do work
}
} else {
for (let j = startMonth; j <= 12; j++){
//Do work
}
}
}
Does someone have a better solution? I feel like this is really clunky. I don't mind using third party packages so if moment or something will work then I'll use it.
Here is what you want :
const start = moment.utc('2018-12');
const end = moment.utc('2020-02');
const year = end.diff(start, 'years');
const month = end.diff(start, 'months')
console.log(start, end);
console.log(year, month);// 1 14
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
First off, be aware that months run from 0 to 11 so January is 0 not 1!
JavaScript's Date class automatically handles "overflows". So for example a date
new Date(2010, 12, 1)
automatically becomes "January 1st, 2011".
This can be used to simply increment just the month of a date:
const currentDate = new Date(2010, 0, 1);
const endDate = new Date();
endMonth.setMonth(endMonth.getMonth() + 1);
while (currentDate.getFullYear() != endMonth.getFullYear() && currentDate.getMonth() != endMonth.getMonth()) {
// Do something
currentDate.setMonth(currentDate.getMonth() + 1);
}
(Watch out that is could result in an endless loop if the start date is already after the end date.)
Here is a slight improvement without adding a third party library:
//Get the current year and month
let currentTime = new Date();
let currentYear = currentTime.getFullYear();
let currentMonth = currentTime.getMonth() + 1;
//Set starting year and month
let startYear = 2010;
let startMonth = 1;
//Loop through the years and months
for (let i = startYear; i <= currentYear; i++){
for (let j = startMonth; j <= (i == currentYear ? currentMonth: 12); j++){
//Do work
}
}

Creating an array of dates between 2 dates

I have 2 dates: startdate and enddate. End date is always a day less than the startdate. So if my start day is 19th, the end date would be on the 18th of next month.
I am trying to create an array of number of days in between the 2 dates.
(It goes from 19th to 18th and then 18th to 18th of every month to calculate the difference)
Example
8/19/2018 - 9/18/2018 = 30 days
9/18/2018 - 10/18/2019 = 30 days
10/18/2018 - 11/18/2018 = 31 days
array = [30,30,31]
I am using the following code to calculate days difference between the dates.
function daysBetweenArrears (date1, date2){
date1.setDate(date1.getDate() );
date2.setDate(date2.getDate() - 1);
var Diff = Math.abs(date2.getTime() - date1.getTime());
var TimeDifference = Math.round(Diff / (1000 * 3600 * 24));
return TimeDifference;
}
The following code for creating the array
if (document.getElementById("endDate"))
y = document.getElementById("endDate").value;
if (document.getElementById("startDate"))
z = document.getElementById("startDate").value;
var dateArr = getDateArray(z, y);
var dayCountArr = "";
var b = [];
for (var x = 0; x < dateArr.length-1; x++)
{
dayCountArr += daysBetweenArrears(dateArr[x], dateArr[x+1], ",");
b.push(daysBetweenArrears(dateArr[x], dateArr[x+1]));
}
The issue is that when i set the date as following, it is giving me incorrect output. The problem is that it is setting the dates incorrectly whenever it goes to the next month. I am not sure what i am doing wrong here. Any help is greatly appreciated. Thank you.
date2.setDate(date2.getDate() - 1);
You can do this using moment. Hope this helps.
const start = "8/19/2018";
const end = "11/18/2018 ";
const dates = [];
const mstart = moment(new Date(start));
const mend = moment(new Date(end));
for (let i = 0; mstart < mend ; i++) {
const daysInMonth = mstart.daysInMonth() + (i === 0 ? -1 : 0);
dates.push(daysInMonth);
mstart.add(1, 'M');
}
console.log(dates);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
You can update your function daysBetweenArrears
const daysBetweenArrears = (date1, date2) => {
const time1 = new Date(date1).getTime();
const time2 = new Date(date2).getTime();
const diff = Math.abs(time2 - time1);
return Math.round(diff/(1000*60*60*24));
};
console.log(daysBetweenArrears('8/18/2018', '9/18/2018'));
console.log(daysBetweenArrears('6/18/2018', '7/18/2018'));

How can I use moment.js to add days, excluding weekends?

I'm setting a default follow-up date two days from current date, which currently works:
const Notify = moment().add(2, 'days').toDate();
However, I would like to exclude weekends. So I installed moment WeekDay, but I can't seem to get it to work with adding days to the current date. The documentation calls for:
moment().weekday(0)
But I can't get that to work with adding in two days forward. Any ideas?
This solution is simple, easy to follow, and works well for me:
function addBusinessDays(originalDate, numDaysToAdd) {
const Sunday = 0;
const Saturday = 6;
let daysRemaining = numDaysToAdd;
const newDate = originalDate.clone();
while (daysRemaining > 0) {
newDate.add(1, 'days');
if (newDate.day() !== Sunday && newDate.day() !== Saturday) {
daysRemaining--;
}
}
return newDate;
}
Try: moment-business-days
It should help you.
Example:
var momentBusinessDays = require("moment-business-days")
momentBusinessDays('20-09-2018', 'DD-MM-YYYY').businessAdd(3)._d
Result:
Tue Sep 25 2018 00:00:00 GMT+0530 (IST)
You could also not use external lib and do a simple function like one of these two:
const WEEKEND = [moment().day("Saturday").weekday(), moment().day("Sunday").weekday()]
const addBusinessDays1 = (date, daysToAdd) => {
var daysAdded = 0,
momentDate = moment(new Date(date));
while (daysAdded < daysToAdd) {
momentDate = momentDate.add(1, 'days');
if (!WEEKEND.includes(momentDate.weekday())) {
daysAdded++
}
}
return momentDate;
}
console.log(addBusinessDays1(new Date(), 7).format('MM/DD/YYYY'))
console.log(addBusinessDays1('09-20-2018', 3).format('MM/DD/YYYY'))
// This is the somewhat faster version
const addBusinessDays2 = (date, days) => {
var d = moment(new Date(date)).add(Math.floor(days / 5) * 7, 'd');
var remaining = days % 5;
while (remaining) {
d.add(1, 'd');
if (d.day() !== 0 && d.day() !== 6)
remaining--;
}
return d;
};
console.log(addBusinessDays2(new Date(), 7).format('MM/DD/YYYY'))
console.log(addBusinessDays2('09-20-2018', 3).format('MM/DD/YYYY'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
They are slightly modified from this post and I think are a good alternative to external library you have to carry/deal with (assuming this is the only part you need and not other features of that lib).
This will do it based on any starting date, and without a costly loop. You calculate the number of weekend days you need to skip over, then just offset by the number of weekdays and weekends, together.
function addWeekdays(year, month, day, numberOfWeekdays) {
var originalDate = year + '-' + month + '-' + day;
var futureDate = moment(originalDate);
var currentDayOfWeek = futureDate.day(); // 0 = Sunday, 1 = Monday, ..., 6 = Saturday
var numberOfWeekends = Math.floor((currentDayOfWeek + numberOfWeekdays - 1) / 5); // calculate the number of weekends to skip over
futureDate.add(numberOfWeekdays + numberOfWeekends * 2, 'days'); // account for the 2 days per weekend
return futureDate;
}
const addWorkingDays = (date: Moment, days: number) => {
let newDate = date.clone();
for (let i = 0; i < days; i++) {
if (newDate.isoWeekday() !== 6 && newDate.isoWeekday() !== 7) {
newDate = newDate.add(1, "days");
} else {
newDate = newDate.add(1, "days");
i--;
}
}
return newDate.format("YYYY/MM/DD");
};
var moment = require("moment")
function addWorkingDay(date, days){
let daysToAdd = days
const today = moment(date);
const nextWeekStart = today.clone().add(1, 'week').weekday(1);
const weekEnd = today.clone().weekday(5);
const daysTillWeekEnd = Math.max(0, weekEnd.diff(today, 'days'));
if(daysTillWeekEnd >= daysToAdd) return today.clone().add(daysToAdd, 'days');
daysToAdd = daysToAdd - daysTillWeekEnd - 1;
return nextWeekStart.add(Math.floor(daysToAdd/5), 'week').add(daysToAdd % 5, 'days')
}
I think this code will be faster:
var businessDays = 10;
var days = businessDays + Math.floor((Math.min(moment().day(),5)+businessDays)/6)*2;
moment.add(days, 'days');
// using pure JS
function addBusinessDays(originalDate, numDaysToAdd) {
const Sunday = 0;
const Saturday = 6;
let daysRemaining = numDaysToAdd;
const newDate = originalDate;
while (daysRemaining > 0) {
newDate.setDate(newDate.getDate() + 1);
if (newDate.getDay() !== 0 && newDate.getDay() !== 6) {
// skip sunday & saturday
daysRemaining--;
}
}
return newDate;
}
var dt = new Date(); // get date
var business_days = 8;
newDate = addBusinessDays(dt, business_days);
console.log(newDate.toString());

How to get days between date range by using javascript or jquery

In a form, I define a start date, an end date, and weekdays
Example:
Start date: 2017-02-07
End date: 2017-03-07
Weekdays: Monday and Thursday
Now I want to get all Mondays and Thursdays between start date and end date by using Javascript or jQuery.
Who can help me?
Thanks...
Simple code. Codepen
var startDate = new Date('2017-02-07');
var endDate = new Date('2017-02-17');
var monday = [];
var thursday = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
if(d.getDay()==1)
monday.push(d);
else if(d.getDay()==4)
thursday.push(d);
}
You can parse date and iterate over increment 1 day and getDay to map with sun(0) to sat(6)
var startDate = new Date("2017-02-07");
var endDate = new Date("2017-03-07");
var totalMon = [];
var totalThu = [];
for (var i = startDate; i <= endDate; ){
if (i.getDay() == 1){
totalMon.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
if (i.getDay() == 4){
totalThu.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
i.setTime(i.getTime() + 1000*60*60*24);
}
console.log(totalMon.length ,totalMon);
console.log(totalThu.length ,totalThu);
Below code finds number of Mondays. You can modify it to calculate any day. It basically finds the difference of days in two dates. Divide it by 7 (this is the number of times everyday will come). Now for pending days loop through the dates and check if a desired day comes in this loop.
var startDate = new Date(2017, 02, 07);
var endDate = new Date(2017, 03, 07);
var dayDiff = Math.round((endDate-startDate)/(1000*60*60*24));
var numberOfMondays = Math.floor(dayDiff/7);
var remainingDays = dayDiff%7;
for(i=0;i<remainingDays;i++)
{
var dateObj = new Date();
dateObj.setDate(endDate.getDate() - i);
if(dateObj.getDay() == 2)
numberOfMondays=numberOfMondays+1;
}
alert(numberOfMondays);
PS : the other two answer are looping through all the dates. I will not suggest this. In code above the number of iterations in loop will never exceed 6 irrespective of the difference in dates.

Categories

Resources