How to loop through weekdays in a month? - javascript

monthDays = 31;
dayOfMonth = 9;
weekOfMonth = 2;
startDay = weekStartingDate (weekOfMonth); // function return 8
// startDay could be 8, 15, 22 or 28
for (var day = startDay; day < (startDay+7) ; day++)
{
//stuff
}
The problem is, when startDay is 29+, that (startDay+7) exceds monthDays
I want to loop through days considering weekdays ranges.

You should define the limit value to your for loop
for (var day = startDay; day < ((startDay+7) > monthDays ? monthDays : (startDay+7)) ; day++)
{
//stuff
}

monthDays = 31;
dayOfMonth = 9;
weekOfMonth = 2;
startDay = weekStartingDate (weekOfMonth); // function return 8
for (var day = startDay; day < (startDay+7) ; day++)
{
//stuff
if(x >=31 ){
break;
}
}

Why not use a tertiary?
monthDays = 31;
dayOfMonth = 9;
weekOfMonth = 2;
startDay = weekStartingDate (weekOfMonth); // function return 8
var maxDay = (startDay+7) > monthDays ? monthDays : (startDay+7)
// startDay could be 8, 15, 22 or 28
for (var day = startDay; day <= maxDay ; day++)
{
//stuff
}

Instead of (startDay+7) use (startDay+7)%monthDays

Not quite sure what you are trying to do, but it seem you are trying to get the dates for a week that are in the same month.
The functions below do that. getWeekStartDate returns a Date for the start of the week for a given date, optionally starting on Monday or Sunday. getNext7DatesInMonth gets up to 7 days from the given a date in the same month.
The result is an array of numbers for the required dates.
/*
** #param {Date} date
** #param {boolean} weekStartsOnMon - true if week starts on Monday
** #returns {Date} - new date object for first day of week
*/
function getWeekStartDate(date, weekStartsOnMon) {
var d = new Date(+date);
var dayNum = d.getDay();
// If start of week is Monday
if (weekStartsOnMon) {
d.setDate(d.getDate() - (dayNum? dayNum : 7) +1)
;
// If start of week is Sunday
} else {
d.setDate(d.getDate() - d.getDay());
}
return d;
}
/*
** For the given date, get the dates in the week for the same month.
**
** #param {Date} date
** #param {boolean} weekStartsOnMon - true if week starts on Monday
** #returns {Array} - String dates for rest of week in same month as date
*/
function getNext7DatesInMonth(date){
var start = new Date(+date);
var monthNum = start.getMonth();
var weekDates = [];
var i = 7;
while (monthNum == start.getMonth() && i--) {
weekDates.push(start.getDate());
start.setDate(start.getDate() + 1);
}
return weekDates;
}
// Start week on Sunday
var d = new Date(2015,4,31)
console.log(d + ': ' + getNext7DatesInMonth(getWeekStartDate(d, false))); // 31
// Start week on Monday
var d = new Date(2015,4,31)
console.log(d + ': ' + getNext7DatesInMonth(getWeekStartDate(d, true))); // 25,26,27,28,29,30,31
You could do a similar function without Date objects based on getting the number of days in the month, but Date objects are convenient.

Related

Get end date from a given start date , weekdays and number of occuring of executions

I am new to programming. I am using javascript right now. I wanted codes to get end date for a execution. I have got Startdate, weekdays(days in which execution occures) and number of executions to occure. How can i get end date???
For example Start date is '15 - 03 - 2018'
days to be executed are Sunday ie '0' and friday '5'
Number of executions from start date to end date is 5
End date of execution here should be '30-03-2018' which is to be retrieved.
Any idea...
Hope this helps.
var date = new Date(2018,2,15); // set date to 15-Mar-2018
var weekdays = [0,6]; // set weekdays
var noOfExcution = 3;
var day = 7 - date.getDay(); //calculate first week days
noOfExcution -= weekdays.filter(x=>x>=date.getDay()).length;
day += noOfExcution % weekdays.length > 0
? weekdays[noOfExcution % weekdays.length - 1]
: weekdays[weekdays.length-1]; //calulate last week days
var x = Math.floor((noOfExcution-0.1) / weekdays.length) * 7 +
day; //calculate in between dates
date.setDate(date.getDate() + x); //setting end date
console.log(date.toLocaleString()); //printing end date
It can be done like this. I somehow figured out a method.
function calcDate() {
var type="weekly";
var date1=new Date('2018,mar,18');
var date2;
var gdays=[];
gdays[0]=0;
gdays[1]=1;
count=10;
if(type=="weekly"){
var d1=date1.getDate();
var year=date1.getFullYear();
var month=date1.getMonth();
while(count>0){
var temp=[];
var tempdays=[];
tempdays=getDaysInMonth(month,year,d1);
console.log(tempdays);
for(var i=0;i<=gdays.length-1;i++) {
var on=gdays[i];
var ddd=days(year,month,on);
for(var j=0;j<=ddd.length-1;j++){
temp.push(ddd[j]);
}
}
temp.sort(function(a, b){return a-b});
console.log(temp);
for(var k=0;k<=temp.length-1;k++){
if(tempdays.includes(temp[k])){
var finalday=temp[k];
count--;
alert("count" +count);
if(count==0) break;
}
}
if(count==0){
alert("final day"+finalday);
date2=new Date(year,month,finalday);
alert(date2);
}
if(count>0){
d1=0;
month=month+1;
if(month>11){
month=0;
year=year+1;
}
}
}
}
function days(year,month,on){
var day, counter, date;
var days=[];
day = 1;
counter = 0;
date = new Date(year, month, day);
while (date.getMonth() === month) {
if (date.getDay() ==on) { // Sun=0, Mon=1, Tue=2, etc.
days[counter]=date.getDate();
counter += 1;
}
day += 1;
date = new Date(year, month, day);
}
return(days);
}
function getDaysInMonth(month, year,day) {
day++;
alert(day);
var date = new Date(year, month, day);
var days = [];
while (date.getMonth() === month) {
var i=date.getDate();
days.push(i);
date.setDate(date.getDate()+1);
}
return days;
}
}

Add Working Days to a Date Using JavaScript

How can I use JavaScript to add working days (i.e. Mon - Friday) automatically adding weekends where necessary?
So if I were to add 5 working days to today (Tue. 22nd Nov. 2016) the result should be "Tue. 29th Nov. 2016" and not "Sun. 27th Nov. 2016".
It is possible to use Date's setDate function (in combination with getDate) to add days onto a date i.e. -
var myDate = new Date(); // Tue 22/11/2016
myDate.setDate(myDate.getDate() + 3); // Fri 25/11/2016
So once you've calculated the number of weekend days within the workdays period you can add that and the required number of workdays to the start date to get the final date.
This function should work though obviously this will not take account of national holidays -
function addWorkDays(startDate, days) {
if(isNaN(days)) {
console.log("Value provided for \"days\" was not a number");
return
}
if(!(startDate instanceof Date)) {
console.log("Value provided for \"startDate\" was not a Date object");
return
}
// Get the day of the week as a number (0 = Sunday, 1 = Monday, .... 6 = Saturday)
var dow = startDate.getDay();
var daysToAdd = parseInt(days);
// If the current day is Sunday add one day
if (dow == 0)
daysToAdd++;
// If the start date plus the additional days falls on or after the closest Saturday calculate weekends
if (dow + daysToAdd >= 6) {
//Subtract days in current working week from work days
var remainingWorkDays = daysToAdd - (5 - dow);
//Add current working week's weekend
daysToAdd += 2;
if (remainingWorkDays > 5) {
//Add two days for each working week by calculating how many weeks are included
daysToAdd += 2 * Math.floor(remainingWorkDays / 5);
//Exclude final weekend if remainingWorkDays resolves to an exact number of weeks
if (remainingWorkDays % 5 == 0)
daysToAdd -= 2;
}
}
startDate.setDate(startDate.getDate() + daysToAdd);
return startDate;
}
//And use it like so (months are zero based)
var today = new Date(2016, 10, 22);
today = addWorkDays(today, 5); // Tue Nov 29 2016 00:00:00 GMT+0000 (GMT Standard Time)
It could also be added to the Date prototype -
Date.prototype.addWorkDays = function (days) {
if(isNaN(days)) {
console.log("Value provided for \"days\" was not a number");
return
}
// Get the day of the week as a number (0 = Sunday, 1 = Monday, .... 6 = Saturday)
var dow = this.getDay();
var daysToAdd = parseInt(days);
// If the current day is Sunday add one day
if (dow == 0) {
daysToAdd++;
}
// If the start date plus the additional days falls on or after the closest Saturday calculate weekends
if (dow + daysToAdd >= 6) {
//Subtract days in current working week from work days
var remainingWorkDays = daysToAdd - (5 - dow);
//Add current working week's weekend
daysToAdd += 2;
if (remainingWorkDays > 5) {
//Add two days for each working week by calculating how many weeks are included
daysToAdd += 2 * Math.floor(remainingWorkDays / 5);
//Exclude final weekend if the remainingWorkDays resolves to an exact number of weeks
if (remainingWorkDays % 5 == 0)
daysToAdd -= 2;
}
}
this.setDate(this.getDate() + daysToAdd);
};
//And use it like so (months are zero based)
var today = new Date(2016, 10, 22)
today.addWorkDays(5); // Tue Nov 29 2016 00:00:00 GMT+0000 (GMT Standard Time)
If it's for adding a few days, not thousands of days, then this is easier and more readable:
const currentDate = new Date('2021-11-18');
console.log(currentDate.toString()); // "Thu Nov 18 2021 00:00:00 GMT+0000"
const numToAdd = 5;
for (let i = 1; i <= numToAdd; i++) {
currentDate.setDate(currentDate.getDate() + 1);
if (currentDate.getDay() === 6) {
currentDate.setDate(currentDate.getDate() + 2);
}
else if (currentDate.getDay() === 0) {
currentDate.setDate(currentDate.getDate() + 1);
}
}
console.log(currentDate.toString()); // "Thu Nov 25 2021 00:00:00 GMT+0000"
I think you can use moment-business-days.
Example:
// 22-11-2016 is Tuesday, DD-MM-YYYY is the format
moment('22-11-2016', 'DD-MM-YYYY').businessAdd(5)._d // Tue Nov 29 2016 00:00:00 GMT-0600 (CST)
const date = new Date('2000-02-02')
const daysToAdd = mapToWorkdays(date, 37)
date.setUTCDate(date.getUTCDate() + daysToAdd)
console.log( date.toISOString().split('T')[0] )
// prints 2000-03-24
/**
* #param {Date} date starting date
* #param {number} add number of workdays to add
* #return {number} total number of days to add to reach correct date
*/
function mapToWorkdays(date, add) {
const wd = weekday(date)
let r = Math.trunc(add / 5) * 2
const rem = add % 5
if (wd > 4) r += (6-wd)
else if (wd+rem > 4) r += 2
return add + r
}
/**
* #param {Date} date
* #return {number} day of the week in range of 0..6 (monday..sunday)
*/
function weekday(date) { return (date.getUTCDay()+ 6) % 7 }
Updated above script to also subtract workdays if negative days are given...
function addWorkDays(startDate, days) {
var isAddingDays = (days > 0);
var isDaysToAddMoreThanWeek = (days > 5 || days < -5);
if (isNaN(days)) {
console.log("Value provided for \"days\" was not a number");
return
}
if (!(startDate instanceof Date)) {
console.log("Value provided for \"startDate\" was not a Date object");
return
}
var dow = startDate.getDay();
var daysToAdd = parseInt(days);
if ((dow === 0 && isAddingDays) || (dow === 6 && !isAddingDays)) {
daysToAdd = daysToAdd + (1 * (isAddingDays ? 1 : -1));
} else if ((dow === 6 && isAddingDays) || (dow === 0 && !isAddingDays)) {
daysToAdd = daysToAdd + (2 * (isAddingDays ? 1 : -1));
}
if (isDaysToAddMoreThanWeek) {
daysToAdd = daysToAdd + (2 * (Math.floor(days / 5)));
if (days % 5 != 0)
daysToAdd = daysToAdd + (2 * (isAddingDays ? -1 : 1));
}
startDate.setDate(startDate.getDate() + daysToAdd);
var newDate = moment(startDate).format('MM/DD/YYYY');
return newDate;
}
This is my simplyest final solution for me:
function addWorkDays(startDate, daysToAdd) {
let dw=startDate.getDay(); //* see note
startDate.setDate(startDate.getDate()-((dw==6)?1:(dw==0)?2:0)); //*
var avance = 2 * Math.floor(daysToAdd / 5); //add 2 days for each 5 workdays
var exceso = (daysToAdd % 5) + startDate.getDay() ;
if (exceso>=6) avance +=2 ;
startDate.setDate(startDate.getDate() + daysToAdd + avance);
return startDate;
}
// If used only with business day dates, the first two lines are not required

total number of sundays in a month

I am using following code to determine total number of sundays in a month, however it gives incorrect result
function sundaysInMonth(start) {
var dat = new Date('1 ' + start);
var y = dat.getFullYear();
var m = dat.getMonth() + 1;
var days = new Date( y,m,0 ).getDate();
var sundays = [ 8 - (new Date( m + '/01/' + y ).getDay()) ];
for ( var i = sundays[0] + 7; i < days; i += 7 ) {
sundays.push( i );
}
return sundays.length;
}
When I call above functions like console.log(sundaysInMonth('September 2013')); then it returns 4 whereas September 2013 has 5 sundays.
I am getting above code from this post
Loops are not needed for this calculation.
function sundaysInMonth(start) {
var d = new Date('1 ' + start); // May not parse in all browsers
var ndays = new Date( d.getFullYear(), d.getMonth()+1, 0 ).getDate();
return Math.floor((ndays + (d.getDay() + 6) % 7) / 7);
}
Test for all months in 2013: http://jsfiddle.net/rGN28/2/
Aw, Matt beat me by one minute! I came up with basically the same solution, only with more comments. ;)
function sundaysInMonth(sMonthAndYear) {
// Get the year and month as integers
var dDate = new Date('1 ' + sMonthAndYear);
var y = dDate.getFullYear();
var m = dDate.getMonth() + 1;
// Get the number of days in the month
var iDayCount = new Date( y,m,0 ).getDate();
// Find the first Sunday
var iFirstSunday = (8 - dDate.getDay());
if (iFirstSunday > 7) {iFirstSunday = 1};
// Calculate the total number of Sundays in the month
var iSundayCount = Math.ceil ((iDayCount + 1 - iFirstSunday) / 7);
// Return the count
return iSundayCount;
}
Check this. I just fixed issue in your code
function sundaysInMonth(start) {
var dat = new Date('1 ' + start);
var y = dat.getFullYear();
var m = dat.getMonth() + 1;
var days = new Date( y,m,0 ).getDate();
var sundays = [ (8 - (new Date( m + '/01/' + y ).getDay())) % 7 ];
for ( var i = sundays[0] + 7; i < days; i += 7 ) {
sundays.push( i );
}
return sundays.length;
}
In array variable sundays we need to intially store the first day value which is a sunday. There was a small bug for months with Day 1 is sunday. For example as in your question September 2013
For these months your code will store 8 instead of 1 sundays array as first sunday. I fixed it
Although the question is old but here is my attempt to find number of Sundays in a month if anyone needs help.
<?php
$year = 2020; // Year to check
$month = 1; // Month to check (1-12)
// Get the first and last day of the month as timestamps
$firstDay = strtotime("{$year}-{$month}-01");
$lastDay = strtotime("+1 month", $firstDay);
// Initialize a counter variable
$numSundays = 0;
// Loop through each day of the month
for ($i = $firstDay; $i < $lastDay; $i = strtotime("+1 day", $i)) {
// Get the day of the week for the current day
$dayOfWeek = date("l", $i);
// If the day is Sunday, increment the counter
if ($dayOfWeek == "Sunday") {
$numSundays++;
}
}
// Print the number of Sundays
echo "Number of Sundays: $numSundays\n";
?>

JavaScript Date.getWeek()? [duplicate]

This question already has answers here:
Get week of year in JavaScript like in PHP
(23 answers)
Closed 5 years ago.
I'm looking for a tested solid solution for getting current week of the year for specified date. All I can find are the ones that doesn't take in account leap years or just plain wrong. Does anyone have this type of stuff?
Or even better a function that says how many weeks does month occupy. It is usually 5, but can be 4 (feb) or 6 (1st is sunday and month has 30-31 days in it)
=================
UPDATE:
Still not sure about getting week #, but since I figured out it won't solve my problem with calculating how many weeks month occupy, I abandoned it.
Here's a function to find out how many weeks exactly month occupy on the calendar:
getWeeksNum: function(year, month) {
var daysNum = 32 - new Date(year, month, 32).getDate(),
fDayO = new Date(year, month, 1).getDay(),
fDay = fDayO ? (fDayO - 1) : 6,
weeksNum = Math.ceil((daysNum + fDay) / 7);
return weeksNum;
}
/**
* Returns the week number for this date. dowOffset is the day of week the week
* "starts" on for your locale - it can be from 0 to 6. If dowOffset is 1 (Monday),
* the week returned is the ISO 8601 week number.
* #param int dowOffset
* #return int
*/
Date.prototype.getWeek = function (dowOffset) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */
dowOffset = typeof(dowOffset) == 'number' ? dowOffset : 0; //default dowOffset to zero
var newYear = new Date(this.getFullYear(),0,1);
var day = newYear.getDay() - dowOffset; //the day of week the year begins on
day = (day >= 0 ? day : day + 7);
var daynum = Math.floor((this.getTime() - newYear.getTime() -
(this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
var weeknum;
//if the year starts before the middle of a week
if(day < 4) {
weeknum = Math.floor((daynum+day-1)/7) + 1;
if(weeknum > 52) {
nYear = new Date(this.getFullYear() + 1,0,1);
nday = nYear.getDay() - dowOffset;
nday = nday >= 0 ? nday : nday + 7;
/*if the next year starts before the middle of
the week, it is week #1 of that year*/
weeknum = nday < 4 ? 1 : 53;
}
}
else {
weeknum = Math.floor((daynum+day-1)/7);
}
return weeknum;
};
Usage:
var mydate = new Date(2011,2,3); // month number starts from 0
// or like this
var mydate = new Date('March 3, 2011');
alert(mydate.getWeek());
Source
For those looking for a more simple approach;
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
var today = new Date(this.getFullYear(),this.getMonth(),this.getDate());
var dayOfYear = ((today - onejan + 86400000)/86400000);
return Math.ceil(dayOfYear/7)
};
Use with:
var today = new Date();
var currentWeekNumber = today.getWeek();
console.log(currentWeekNumber);
Consider using my implementation of "Date.prototype.getWeek", think is more accurate than the others i have seen here :)
Date.prototype.getWeek = function(){
// We have to compare against the first monday of the year not the 01/01
// 60*60*24*1000 = 86400000
// 'onejan_next_monday_time' reffers to the miliseconds of the next monday after 01/01
var day_miliseconds = 86400000,
onejan = new Date(this.getFullYear(),0,1,0,0,0),
onejan_day = (onejan.getDay()==0) ? 7 : onejan.getDay(),
days_for_next_monday = (8-onejan_day),
onejan_next_monday_time = onejan.getTime() + (days_for_next_monday * day_miliseconds),
// If one jan is not a monday, get the first monday of the year
first_monday_year_time = (onejan_day>1) ? onejan_next_monday_time : onejan.getTime(),
this_date = new Date(this.getFullYear(), this.getMonth(),this.getDate(),0,0,0),// This at 00:00:00
this_time = this_date.getTime(),
days_from_first_monday = Math.round(((this_time - first_monday_year_time) / day_miliseconds));
var first_monday_year = new Date(first_monday_year_time);
// We add 1 to "days_from_first_monday" because if "days_from_first_monday" is *7,
// then 7/7 = 1, and as we are 7 days from first monday,
// we should be in week number 2 instead of week number 1 (7/7=1)
// We consider week number as 52 when "days_from_first_monday" is lower than 0,
// that means the actual week started before the first monday so that means we are on the firsts
// days of the year (ex: we are on Friday 01/01, then "days_from_first_monday"=-3,
// so friday 01/01 is part of week number 52 from past year)
// "days_from_first_monday<=364" because (364+1)/7 == 52, if we are on day 365, then (365+1)/7 >= 52 (Math.ceil(366/7)=53) and thats wrong
return (days_from_first_monday>=0 && days_from_first_monday<364) ? Math.ceil((days_from_first_monday+1)/7) : 52;
}
You can check my public repo here https://bitbucket.org/agustinhaller/date.getweek (Tests included)
Get week number
Date.prototype.getWeek = function() {
var dt = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - dt) / 86400000) + dt.getDay()+1)/7);
};
var myDate = new Date(2013, 3, 25); // 2013, 25 April
console.log(myDate.getWeek());
I know this is an old question, but maybe it helps:
http://weeknumber.net/how-to/javascript
// This script is released to the public domain and may be used, modified and
// distributed without restrictions. Attribution not necessary but appreciated.
// Source: https://weeknumber.net/how-to/javascript
// Returns the ISO week of the date.
Date.prototype.getWeek = function() {
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), 0, 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000
- 3 + (week1.getDay() + 6) % 7) / 7);
}
// Returns the four-digit year corresponding to the ISO week of the date.
Date.prototype.getWeekYear = function() {
var date = new Date(this.getTime());
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
return date.getFullYear();
}
/*get the week number by following the norms of ISO 8601*/
function getWeek(dt){
var calc=function(o){
if(o.dtmin.getDay()!=1){
if(o.dtmin.getDay()<=4 && o.dtmin.getDay()!=0)o.w+=1;
o.dtmin.setDate((o.dtmin.getDay()==0)? 2 : 1+(7-o.dtmin.getDay())+1);
}
o.w+=Math.ceil((((o.dtmax.getTime()-o.dtmin.getTime())/(24*60*60*1000))+1)/7);
},getNbDaysInAMonth=function(year,month){
var nbdays=31;
for(var i=0;i<=3;i++){
nbdays=nbdays-i;
if((dtInst=new Date(year,month-1,nbdays)) && dtInst.getDate()==nbdays && (dtInst.getMonth()+1)==month && dtInst.getFullYear()==year)
break;
}
return nbdays;
};
if(dt.getMonth()+1==1 && dt.getDate()>=1 && dt.getDate()<=3 && (dt.getDay()>=5 || dt.getDay()==0)){
var pyData={"dtmin":new Date(dt.getFullYear()-1,0,1,0,0,0,0),"dtmax":new Date(dt.getFullYear()-1,11,getNbDaysInAMonth(dt.getFullYear()-1,12),0,0,0,0),"w":0};
calc(pyData);
return pyData.w;
}else{
var ayData={"dtmin":new Date(dt.getFullYear(),0,1,0,0,0,0),"dtmax":new Date(dt.getFullYear(),dt.getMonth(),dt.getDate(),0,0,0,0),"w":0},
nd12m=getNbDaysInAMonth(dt.getFullYear(),12);
if(dt.getMonth()==12 && dt.getDay()!=0 && dt.getDay()<=3 && nd12m-dt.getDate()<=3-dt.getDay())ayData.w=1;else calc(ayData);
return ayData.w;
}
}
alert(getWeek(new Date(2017,01-1,01)));

Get Weeks In Month Through Javascript

In Javascript, how do I get the number of weeks in a month? I can't seem to find code for this anywhere.
I need this to be able to know how many rows I need for a given month.
To be more specific, I would like the number of weeks that have at least one day in the week (a week being defined as starting on Sunday and ending on Saturday).
So, for something like this, I would want to know it has 5 weeks:
S M T W R F S
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Thanks for all the help.
Weeks start on Sunday
This ought to work even when February doesn't start on Sunday.
function weekCount(year, month_number) {
// month_number is in the range 1..12
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var used = firstOfMonth.getDay() + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
Weeks start on Monday
function weekCount(year, month_number) {
// month_number is in the range 1..12
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var used = firstOfMonth.getDay() + 6 + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
Weeks start another day
function weekCount(year, month_number, startDayOfWeek) {
// month_number is in the range 1..12
// Get the first day of week week day (0: Sunday, 1: Monday, ...)
var firstDayOfWeek = startDayOfWeek || 0;
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var numberOfDaysInMonth = lastOfMonth.getDate();
var firstWeekDay = (firstOfMonth.getDay() - firstDayOfWeek + 7) % 7;
var used = firstWeekDay + numberOfDaysInMonth;
return Math.ceil( used / 7);
}
None of the solutions proposed here don't works correctly, so I wrote my own variant and it works for any cases.
Simple and working solution:
/**
* Returns count of weeks for year and month
*
* #param {Number} year - full year (2016)
* #param {Number} month_number - month_number is in the range 1..12
* #returns {number}
*/
var weeksCount = function(year, month_number) {
var firstOfMonth = new Date(year, month_number - 1, 1);
var day = firstOfMonth.getDay() || 6;
day = day === 1 ? 0 : day;
if (day) { day-- }
var diff = 7 - day;
var lastOfMonth = new Date(year, month_number, 0);
var lastDate = lastOfMonth.getDate();
if (lastOfMonth.getDay() === 1) {
diff--;
}
var result = Math.ceil((lastDate - diff) / 7);
return result + 1;
};
you can try it here
This is very simple two line code. and i have tested 100%.
Date.prototype.getWeekOfMonth = function () {
var firstDay = new Date(this.setDate(1)).getDay();
var totalDays = new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
return Math.ceil((firstDay + totalDays) / 7);
}
How to use
var totalWeeks = new Date().getWeekOfMonth();
console.log('Total Weeks in the Month are : + totalWeeks );
You'll have to calculate it.
You can do something like
var firstDay = new Date(2010, 0, 1).getDay(); // get the weekday january starts on
var numWeeks = 5 + (firstDay >= 5 ? 1 : 0); // if the months starts on friday, then it will end on sunday
Now we just need to genericize it.
var dayThreshold = [ 5, 1, 5, 6, 5, 6, 5, 5, 6, 5, 6, 5 ];
function GetNumWeeks(month, year)
{
var firstDay = new Date(year, month, 1).getDay();
var baseWeeks = (month == 1 ? 4 : 5); // only February can fit in 4 weeks
// TODO: account for leap years
return baseWeeks + (firstDay >= dayThreshold[month] ? 1 : 0); // add an extra week if the month starts beyond the threshold day.
}
Note: When calling, remember that months are zero indexed in javascript (i.e. January == 0).
function weeksinMonth(m, y){
y= y || new Date().getFullYear();
var d= new Date(y, m, 0);
return Math.floor((d.getDate()- 1)/7)+ 1;
}
alert(weeksinMonth(3))
// the month range for this method is 1 (january)-12(december)
The most easy to understand way is
<div id="demo"></div>
<script type="text/javascript">
function numberOfDays(year, month)
{
var d = new Date(year, month, 0);
return d.getDate();
}
function getMonthWeeks(year, month_number)
{
var $num_of_days = numberOfDays(year, month_number)
, $num_of_weeks = 0
, $start_day_of_week = 0;
for(i=1; i<=$num_of_days; i++)
{
var $day_of_week = new Date(year, month_number, i).getDay();
if($day_of_week==$start_day_of_week)
{
$num_of_weeks++;
}
}
return $num_of_weeks;
}
var d = new Date()
, m = d.getMonth()
, y = d.getFullYear();
document.getElementById('demo').innerHTML = getMonthWeeks(y, m);
</script>
using moment js
function getWeeksInMonth(year, month){
var monthStart = moment().year(year).month(month).date(1);
var monthEnd = moment().year(year).month(month).endOf('month');
var numDaysInMonth = moment().year(year).month(month).endOf('month').date();
//calculate weeks in given month
var weeks = Math.ceil((numDaysInMonth + monthStart.day()) / 7);
var weekRange = [];
var weekStart = moment().year(year).month(month).date(1);
var i=0;
while(i<weeks){
var weekEnd = moment(weekStart);
if(weekEnd.endOf('week').date() <= numDaysInMonth && weekEnd.month() == month) {
weekEnd = weekEnd.endOf('week').format('LL');
}else{
weekEnd = moment(monthEnd);
weekEnd = weekEnd.format('LL')
}
weekRange.push({
'weekStart': weekStart.format('LL'),
'weekEnd': weekEnd
});
weekStart = weekStart.weekday(7);
i++;
}
return weekRange;
} console.log(getWeeksInMonth(2016, 7))
ES6 variant, using consistent zero-based months index. Tested for years from 2015 to 2025.
/**
* Returns number of weeks
*
* #param {Number} year - full year (2018)
* #param {Number} month - zero-based month index (0-11)
* #param {Boolean} fromMonday - false if weeks start from Sunday, true - from Monday.
* #returns {number}
*/
const weeksInMonth = (year, month, fromMonday = false) => {
const first = new Date(year, month, 1);
const last = new Date(year, month + 1, 0);
let dayOfWeek = first.getDay();
if (fromMonday && dayOfWeek === 0) dayOfWeek = 7;
let days = dayOfWeek + last.getDate();
if (fromMonday) days -= 1;
return Math.ceil(days / 7);
}
You could use my time.js library. Here's the weeksInMonth function:
// http://github.com/augustl/time.js/blob/623e44e7a64fdaa3c908debdefaac1618a1ccde4/time.js#L67
weeksInMonth: function(){
var millisecondsInThisMonth = this.clone().endOfMonth().epoch() - this.clone().firstDayInCalendarMonth().epoch();
return Math.ceil(millisecondsInThisMonth / MILLISECONDS_IN_WEEK);
},
It might be a bit obscure since the meat of the functionality is in endOfMonth and firstDayInCalendarMonth, but you should at least be able to get some idea of how it works.
This works for me,
function(d){
var firstDay = new Date(this.getFullYear(), this.getMonth(), 1).getDay();
return Math.ceil((d.getDate() + (firstDay - 1))/7);
}
"d" should be the date.
A little rudimentary, yet should cater for original post :
/**
* #param {date} 2020-01-30
* #return {int} count
*/
this.numberOfCalendarWeekLines = date => {
// get total
let lastDayOfMonth = new Date( new Date( date ).getFullYear(), new Date( date ).getMonth() + 1, 0 );
let manyDaysInMonth = lastDayOfMonth.getDate();
// itterate through month - from 1st
// count calender week lines by occurance
// of a Saturday ( s m t w t f s )
let countCalendarWeekLines = 0;
for ( let i = 1; i <= manyDaysInMonth; i++ ) {
if ( new Date( new Date( date ).setDate( i ) ).getDay() === 6 ) countCalendarWeekLines++;
}
// days after last occurance of Saturday
// leaked onto new line?
if ( lastDayOfMonth.getDay() < 6 ) countCalendarWeekLines++;
return countCalendarWeekLines;
};
Thanks to Ed Poor for his solution, this is the same as Date prototype.
Date.prototype.countWeeksOfMonth = function() {
var year = this.getFullYear();
var month_number = this.getMonth();
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var used = firstOfMonth.getDay() + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
So you can use it like
var weeksInCurrentMonth = new Date().countWeeksOfMonth();
var weeksInDecember2012 = new Date(2012,12,1).countWeeksOfMonth(); // 6
function getWeeksInMonth(month_number, year) {
console.log("year - "+year+" month - "+month_number+1);
var day = 0;
var firstOfMonth = new Date(year, month_number, 1);
var lastOfMonth = new Date(year, parseInt(month_number)+1, 0);
if (firstOfMonth.getDay() == 0) {
day = 2;
firstOfMonth = firstOfMonth.setDate(day);
firstOfMonth = new Date(firstOfMonth);
} else if (firstOfMonth.getDay() != 1) {
day = 9-(firstOfMonth.getDay());
firstOfMonth = firstOfMonth.setDate(day);
firstOfMonth = new Date(firstOfMonth);
}
var days = (lastOfMonth.getDate() - firstOfMonth.getDate())+1
return Math.ceil( days / 7);
}
It worked for me. Please try
Thanks all
This piece of code give you the exact number of weeks in a given month:
Date.prototype.getMonthWeek = function(monthAdjustement)
{
var firstDay = new Date(this.getFullYear(), this.getMonth(), 1).getDay();
var returnMessage = (Math.ceil(this.getDate()/7) + Math.floor(((7-firstDay)/7)));
return returnMessage;
}
The monthAdjustement variable adds or substract the month that you are currently in
I use it in a calendar project in JS and the equivalent in Objective-C and it works well
function weekCount(year, month_number, day_start) {
// month_number is in the range 1..12
// day_start is in the range 0..6 (where Sun=0, Mon=1, ... Sat=6)
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var dayOffset = (firstOfMonth.getDay() - day_start + 7) % 7;
var used = dayOffset + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
I know this is coming late, I have seen codes upon codes trying to get the number of weeks a particular month falls on, but many have not been really precise but most have been really informative and reusable, I'm not an expert programmer but I can really think and thanks to some codes by some people I was able to arrive at a conclusion.
function convertDate(date) {//i lost the guy who owns this code lol
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth()+1).toString();
var dd = date.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}
//this line of code from https://stackoverflow.com/a/4028614/2540911
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var myDate = new Date('2019-03-2');
//var myDate = new Date(); //or todays date
var c = convertDate(myDate).split("-");
let yr = c[0], mth = c[1], dy = c[2];
weekCount(yr, mth, dy)
//Ahh yes, this line of code is from Natim Up there, incredible work, https://stackoverflow.com/a/2485172/2540911
function weekCount(year, month_number, startDayOfWeek) {
// month_number is in the range 1..12
console.log(weekNumber);
// Get the first day of week week day (0: Sunday, 1: Monday, ...)
var firstDayOfWeek = startDayOfWeek || 0;
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var numberOfDaysInMonth = lastOfMonth.getDate();
var first = firstOfMonth.getDate();
//initialize first week
let weekNumber = 1;
while(first-1 < numberOfDaysInMonth){
// add a day
firstOfMonth = firstOfMonth.setDate(firstOfMonth.getDate() + 1);//this line of code from https://stackoverflow.com/a/9989458/2540911
if(days[firstOfMonth.getDay()] === "Sunday"){//get new week every new sunday according the local date format
//get newWeek
weekNumber++;
}
if(weekNumber === 3 && days[firstOfMonth.getDay()] === "Friday")
alert(firstOfMonth);
first++
}
}
I needed this code to generate a schedule or event scheduler for a church on every 3rd friday of a new month, so you can modify this to suit your or just pick your specific date, not "friday and specify the week of the month and Voila!! here you go
None of the solutions here really worked for me. Here is my crack at it.
// Example
// weeksOfMonth(2019, 9) // October
// Result: 5
weeksOfMonth (year, monthIndex) {
const d = new Date(year, monthIndex+ 1, 0)
const adjustedDate = d.getDate() + d.getDay()
return Math.ceil(adjustedDate / 7)
}
Every solutions helped but nothing was working for me so I did my own with moment library :
const getWeeksInAMonth = (currentDate: string) => {
const startOfMonth = moment(currentDate).startOf("month")
const endOfMonth = moment(currentDate).endOf("month")
return moment(endOfMonth).week() - moment(startOfMonth).week() + 1
}

Categories