Get week range for given month and year in JavaScript - javascript

I need to display a range of dates in corresponding week for selected month. Suppose the selected values are month=3 (April) and year=2018. The output should show a list of ranged dates for weeks in that particular month selected.
month = 3;
year = 2018;
Output:
Week 1: 01/04/2018 - 01/04/2018
Week 2: 02/04/2018 - 08/04/2018
Week 3: 09/04/2018 - 15/04/2018
Week 4: 16/04/2018 - 22/04/2018
Week 5: 23/04/2018 - 29/04/2018
Week 6: 30/04/2018 - 30/04/2018
I tried this function but it doesn't work correctly. Can you help me ? thanks a lot.
public getWeeksInMonth(): {
let year: number = 2018;
let month: number = 3 //April;
const weeks = [];
const firstDay: Date = new Date(year, month, 1);
const lastDay: Date = new Date(year, month + 1, 0);
const daysInMonth: number = lastDay.getDate();
let dayOfWeek: number = firstDay.getDay();
let start: number;
let end: number;
for (let i = 1; i < daysInMonth + 1; i++) {
if (dayOfWeek === 0 || i === 1) {
start = i;
}
if (dayOfWeek === 6 || i === daysInMonth) {
end = i;
if ((start !== end) || (start === 30 && end === 30) || (start === 31 && end === 31)) {
weeks.push({
'start': start,
'end': end
});
}
}
dayOfWeek = new Date(year, month, i).getDay();
}
return weeks;
}

The first problem is that sunday gets 0 by .getDay() instead of monday.
Solved this issue checking for dayOfWeek === 1 instead of dayOfWeek === 0 and dayOfWeek === 0 instead of dayOfWeek === 6.
The second problem is your checking befor pushing a new week. You're checking for if start !== end but start could be equal to end
Solved this issue by setting start to null after pushing a new week and checking for start instead.
(Example below is written in JS, because TS is not runable at StackOverflow)
function getWeeksInMonth() {
let year = 2018;
let month = 3; //April;
const weeks = [];
const firstDay = new Date(year, month, 1);
const lastDay = new Date(year, month + 1, 0);
const daysInMonth = lastDay.getDate();
let dayOfWeek = firstDay.getDay();
let start;
let oldstart;
let end;
for (let i = 1; i < daysInMonth + 1; i++) {
if (dayOfWeek === 1 || i === 1) {
start = i;
}
if (dayOfWeek === 0 || i === daysInMonth) {
end = i;
if(start){
weeks.push({
'start': start,
'end': end
});
start = null;
}
}
dayOfWeek = new Date(year, month, i + 1).getDay();
}
return weeks;
}
console.log(getWeeksInMonth());

I have slightly refactored your solution and it seems to deliver expected result.
My code follows exactly the same (brute force) approach as yours:
make up an array (with Array.from()) of length equal to the number of days in a given month and fill it with the dates of each day of that month;
cycle through that array (with Array.prototype.reduce()) and throw into resulting array objects ({week,start,end}) that correspond to weeks, generating new objects as you hit Monday and closing the end date as you hit Sunday:
const getWeeksInMonth = (month, year) =>
Array
.from({length: (new Date(year, month+1, 0) - new Date(year, month, 0))/864E5},
(_,i) => new Date(year, month, i+1))
.reduce((res,date,idx,self) => {
const itsMonday = date.getDay() == 1,
itsSunday = date.getDay() == 0,
monthStart = idx == 0,
monthEnd = idx == self.length-1,
options = {dateStyle: 'short'};
if(itsMonday || monthStart)
res.push({
week:(res[res.length-1]||{week:0}).week+1,
start: date.toLocaleDateString('fr',options),
end: (monthStart ? date.toLocaleDateString('fr',options) : '')
});
if(itsSunday || monthEnd)
res[res.length-1].end = date.toLocaleDateString('fr',options);
return res;
}, []);
console.log(getWeeksInMonth(3,2018));
.as-console-wrapper {min-height:100%}

I found the solution.
Here the complete funtion working correctly:
public getWeeksInMonth(): Observable<Week[]> {
let year: number = 2018;
let month: number = 3;
const weeks: Week[] = [];
const firstDay: Date = new Date(Date.UTC(year, month, 1));
const lastDay: Date = new Date(Date.UTC(year, month + 1, 0));
const daysInMonth: number = lastDay.getDate();
let dayOfWeek: number = firstDay.getDay();
let start: number;
let end: number;
for (let i = 1; i < daysInMonth + 1; i++) {
if (dayOfWeek === 0 || i === 1) {
start = i;
}
if (dayOfWeek === 0 && start === 1 && i !== daysInMonth) {
end = 1;
weeks.push({
'start': start,
'end': end
});
}
if (dayOfWeek === 6 || i === daysInMonth) {
end = i;
if ((start !== end) || (start === 30 && end === 30) || (start === 31 && end === 31)) {
weeks.push({
'start': start,
'end': end
});
}
}
dayOfWeek = new Date(year, month, i).getDay();
}
return of(weeks);
}

Related

JavaScript weekday list get

I need to create a JavaScript function for the below requirements. I need to get every week day date list. If you know nodeJs package tell me that. Thank you for your attention.
Example -
2022-01-03
2022-01-04
2022-01-05
2022-01-06
2022-01-07
2022-01-10
2022-01-11
2022-01-12
2022-01-13
2022-01-14
..........
..........
until year-end
like this pattern (only Monday to Friday)
function getWeekDaysForYear(year) {
const isLeap = year % 4 === 0;
const numberOfDays = isLeap ? 366 : 365;
let currentDate = new Date(Date.UTC(year, 0, 0, 0, 0, 0, 0));
const weekDays = [];
for(let i = 1; i <= numberOfDays; i++) {
currentDate = new Date(currentDate.getTime() + 24 * 3600 * 1000);
if (currentDate.getDay() === 0 || currentDate.getDay() === 6) {
continue;
}
weekDays.push(currentDate.toISOString().split('T')[0]);
}
return weekDays;
}
console.log(getWeekDaysForYear(2022));
This is a simple function which returns all the weekdays for the specified year in an array.
JavaScript's Date object overflows, so you can use:
for (i=1;i<366;i++) {
if (i%7==1 || i%7==2) continue;
const d = new Date(2022, 0, i);
document.write(d.toDateString(),'<br>');
}
You will need to watch for leap years, and recalculate which days are the weekend every year.
Something like this
const endDate = new Date(2022,1,2);
const date = new Date(); //today
while (endDate > date) {
const weekDay = date.getDay();
if (weekDay != 6 && weekDay != 0) {
let year = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(date);
let month = new Intl.DateTimeFormat('en', { month: '2-digit' }).format(date);
let day = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date);
console.log(`${year}-${month}-${day}`);
}
date.setDate(date.getDate() + 1);
}
Since we're play code golf…
function getWeekDays(year) {
// Start on 1 Jan of given year
let d = new Date(Date.UTC(year, 0));
let result = [];
do {
// Only push dates that aren't Sat (6) or Sun (0)
d.getDay() % 6 ? result.push(d.toLocaleDateString('en-CA')) : null;
// Increment date
d.setDate(d.getDate() + 1);
// Until get to 1 Jan again
} while (d.getMonth() + d.getDate() > 1)
return result;
}
console.log(getWeekDays(new Date().getFullYear()))
function getWeekDaysForDateRange(start, end) {
const [startYear, startMonth, startDate] = start.split("-");
const [endYear, endMonth, endDate] = end.split("-");
let beginDate = new Date(Date.UTC(startYear, startMonth - 1, startDate - 1, 0, 0, 0, 0));
let closeDate = new Date(Date.UTC(endYear, endMonth - 1, endDate, 0, 0, 0, 0));
const weekDays = [];
while(beginDate.getTime() !== closeDate.getTime()) {
beginDate = new Date(beginDate.getTime() + 24 * 3600 * 1000);
if (beginDate.getDay() === 0 || beginDate.getDay() === 6) {
continue;
}
weekDays.push(beginDate.toISOString().split('T')[0]);
}
return weekDays;
}
console.log(getWeekDaysForDateRange('2022-01-01', '2022-01-10'));
Something like this would work for date range as you want!

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());

js datepicker - allow non-consecutive days pcm

I would like to limit users to selecting only the first and third Monday of each month. We have a volunteer intake only on these days, so I want to limit incorrect date selections as much as possible.
I'm not a js coder, but have managed to adapt some code I found online to allow the first or third Monday of each month, but I can't work out how to allow both of them.
Here's the code I have for the first Monday:
var firstMonday = new Date(date);
var mondays=0;
firstMonday.setDate(1);
while (mondays < 1) {
firstMonday.setDate(firstMonday.getDate() + 1);
if (firstMonday.getDay() == 1) {
mondays++;
}
}
var result = date.getDate() != firstMonday.getDate();
I think this is what you are asking. Credit to jabclab for the getMondays() function.
// test: first monday of this month
// result: true
//var dates = [new Date(2017,8,4)];
// test: third monday of this month
// result: true
//var dates = [new Date(2017,8,18)];
// test: first and third monday of this month
// result: true
var dates = [new Date(2017,8,4), new Date(2017,8,18)];
// test: first monday, third monday, and random day from this month
// result: false
//var dates = [new Date(2017,8,4), new Date(2017,8,18), new Date(2017,8,22)];
alert(validate(dates));
function validate(dates) {
var valid = true;
var mondays = getMondays();
var firstMonday = mondays[0].setHours(0,0,0,0);
var thirdMonday = mondays[2].setHours(0,0,0,0);
if (dates && dates.length > 0) {
for (var i = 0; i < dates.length; i++) {
// Zero out time so only year, month, and day is compared
var d = dates[i].setHours(0,0,0,0);
if (d != firstMonday && d != thirdMonday) {
return false;
}
}
}
else {
valid = false;
}
return valid;
}
function getMondays() {
var d = new Date(),
month = d.getMonth(),
mondays = [];
d.setDate(1);
// Get the first Monday in the month
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getMonth() === month) {
mondays.push(new Date(d.getTime()));
d.setDate(d.getDate() + 7);
}
return mondays;
}
Thanks, but I'm not sure if the above works or not as I was looking for a js code answer - I'll leave that for someone else to work out.
...which I've found in the meantime. Many thanks to Hugh at Fabrik for the following:
var thisdate = new Date(date);
thisdate.setHours(0,0,0,0);
var day = 1; // monday
var nth = 1; // first
var first = new Date(thisdate.getFullYear(), thisdate.getMonth(), 1),
add = (day - first.getDay() + 7) % 7 + (nth - 1) * 7;
first.setDate(1 + add);
nth = 3; // third
var third = new Date(thisdate.getFullYear(), thisdate.getMonth(), 1),
add = (day - third.getDay() + 7) % 7 + (nth - 1) * 7;
third.setDate(1 + add);
//console.log(thisdate + ', ' + first + ', ' + third);
var result = (first.getTime() !== thisdate.getTime()) && (third.getTime() !== thisdate.getTime());

How to get month and its days in moment?

I'm going to create a calendar using moment.js, now I want to know how to get months and days for each month? I found this code but I didn't understand what it does:
function generateMonth() {
var weeks = [];
var done = false, date = moment().clone(), monthIndex = moment().month(), count = 0;
while (!done) {
weeks.push({ days: generateDays(moment().clone(), moment()) });
date.add(1, "w");
done = count++ > 2 && monthIndex !== date.month();
monthIndex = date.month();
}
}
function generateDays(date, month) {
var days = [];
for (var i = 0; i < 7; i++) {
days.push({
number: date.date(),
isCurrentMonth: date.month() === month.month(),
isToday: date.isSame(new Date(), "day")
});
date = date.clone();
date.add(1, "d");
}
return days;
}

Get a list of dates between two dates using javascript

From JavaScript is there a way to get list of days between two dates from MySQL format. I don't want to use any library for this.
This is what i did.
function generateDateList(from, to) {
var getDate = function(date) { //Mysql Format
var m = date.getMonth(), d = date.getDate();
return date.getFullYear() + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d);
}
var fs = from.split('-'), startDate = new Date(fs[0], fs[1], fs[2]), result = [getDate(startDate)], start = startDate.getTime(), ts, end;
if ( typeof to == 'undefined') {
end = new Date().getTime();
} else {
ts = to.split('-');
end = new Date(ts[0], ts[1], ts[2]).getTime();
}
while (start < end) {
start += 86400000;
startDate.setTime(start);
result.push(getDate(startDate));
}
return result;
}
console.log(generateDateList('2014-2-27', '2014-3-2'));
I test it from chrome and nodejs below are the result.
[ '2014-02-27',
'2014-02-28',
'2014-02-29',
'2014-02-30',
'2014-02-31',
'2014-03-01',
'2014-03-02' ]
yeh big leap year:-D..., how can i fix this? or is there any better way.?
const listDate = [];
const startDate ='2017-02-01';
const endDate = '2017-02-10';
const dateMove = new Date(startDate);
let strDate = startDate;
while (strDate < endDate) {
strDate = dateMove.toISOString().slice(0, 10);
listDate.push(strDate);
dateMove.setDate(dateMove.getDate() + 1);
};
Take the start date and increment it by one day until you reach the end date.
Note: MySQL dates are standard format, no need to parse it by hand just pass it to the Date constructor: new Date('2008-06-13').
const addDays = (date, days = 1) => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
const dateRange = (start, end, range = []) => {
if (start > end) return range;
const next = addDays(start, 1);
return dateRange(next, end, [...range, start]);
};
const range = dateRange(new Date("2014-02-27"), new Date("2014-03-02"));
console.log(range);
console.log(range.map(date => date.toISOString().slice(0, 10)))
Here I use a recursive function, but you could achieve the same thing using a while (see other answers).
I have used this one from
https://flaviocopes.com/how-to-get-days-between-dates-javascript/
const getDatesBetweenDates = (startDate, endDate) => {
let dates = []
//to avoid modifying the original date
const theDate = new Date(startDate)
while (theDate < new Date(endDate)) {
dates = [...dates, new Date(theDate)]
theDate.setDate(theDate.getDate() + 1)
}
dates = [...dates, new Date(endDate)]
return dates
}
Invoke the function as follows:
getDatesBetweenDates("2021-12-28", "2021-03-01")
Note - I just had to fix issues with the Date object creation (new Date()) in the while loop and in the dates array. Other than that the code is pretty much same as seen on the above link
dateRange(startDate, endDate) {
var start = startDate.split('-');
var end = endDate.split('-');
var startYear = parseInt(start[0]);
var endYear = parseInt(end[0]);
var dates = [];
for(var i = startYear; i <= endYear; i++) {
var endMonth = i != endYear ? 11 : parseInt(end[1]) - 1;
var startMon = i === startYear ? parseInt(start[1])-1 : 0;
for(var j = startMon; j <= endMonth; j = j > 12 ? j % 12 || 11 : j+1) {
var month = j+1;
var displayMonth = month < 10 ? '0'+month : month;
dates.push([i, displayMonth, '01'].join('-'));
}
}
return dates;
}
var oDate1 = oEvent.getParameter("from"),
oDate2 = oEvent.getParameter("to");
var aDates = [];
var currentDate = oDate1;
while (currentDate <= oDate2) {
aDates.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
I expanded Công Thắng's great answer to return {years, months, days}, thought it was worth sharing:
function getDates(startDate, endDate) {
const days = [],
months = new Set(),
years = new Set()
const dateMove = new Date(startDate)
let date = startDate
while (date < endDate){
date = dateMove.toISOString().slice(0,10)
months.add(date.slice(0, 7))
years.add(date.slice(0, 4))
days.push(date)
dateMove.setDate(dateMove.getDate()+1) // increment day
}
return {years: [...years], months: [...months], days} // return arrays
}
console.log(getDates('2016-02-28', '2016-03-01')) // leap year
/* =>
{
years: [ '2016' ],
months: [ '2016-02', '2016-03' ],
days: [ '2016-02-28', '2016-02-29', '2016-03-01' ]
}
*/
const {months} = getDates('2016-02-28', '2016-03-01') // get only months
Basically the function just increments the built-in Date object by one day from start to end, while the Sets capture unique months and years.

Categories

Resources