I have a javascript function which calculates the date range from the week number
Date.prototype.getWeek = function weekCalc() {
const date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
date.setDate((date.getDate() + 3 - (date.getDay() + 6)) % 7);
const week1 = new Date(date.getFullYear(), 0, 4);
return 1 + Math.round((((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6)) % 7) / 7);
};
const getDateRangeOfWeek = (weekNo, y) => {
const d1 = new Date(`${y}`);
const pastDays = d1.getDay() - 1;
d1.setDate(d1.getDate() - pastDays);
d1.setDate(d1.getDate() + 7 * (weekNo - d1.getWeek()));
const rangeIsFrom = `${`0${d1.getDate()}`.slice(-2)}/${`0${d1.getMonth() + 1}`.slice(-2)}/${d1.getFullYear().toString().substring(2)}`;
d1.setDate(d1.getDate() + 6);
const rangeIsTo = `${`0${d1.getDate()}`.slice(-2)}/${`0${d1.getMonth() + 1}`.slice(-2)}/${d1.getFullYear().toString().substring(2)}`;
return `${rangeIsFrom}-${rangeIsTo}`;
};
console.log(getDateRangeOfWeek(52, 2016));
When you test it for the week number 52 of year 2016 according to ISO 8061 it gives
getDateRangeOfWeek(52, 2016);
"19/12/16-25/12/16"
which is somehow incorrect, check here https://www.calendar-week.org/2016/52
I'm not sure what's going wrong in the above implementation?
I didn't bother digging through your code, but I did cobble together a solution that will retrieve the desired result:
function addDays(date, days) {
let newDate = new Date(date);
newDate.setDate(newDate.getDate() + days)
return newDate;
}
let locale = new Intl.DateTimeFormat('en-GB',{ dateStyle: 'short'});
function formatDate(date) {
return locale.format(date)
}
function getDateOfISOWeek(w, y) {
let simple = new Date(y, 0, 1 + (w - 1) * 7);
let dow = simple.getDay();
let ISOweekStart = simple;
if (dow <= 4)
ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
else
ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
let ISOweekEnd = addDays(ISOweekStart, 6);
//let dateSpanLong = `${ISOweekStart} to ${ISOweekEnd}`; // date objects to do with what you please;
let dateSpanShort = `${formatDate(ISOweekStart)} to ${formatDate(ISOweekEnd)}`;
return dateSpanShort;
}
console.log(getDateOfISOWeek(52,2016)) // returns '26/12/2016 to 01/01/2017'
Here's a great reference for the Intl.DateTimeFormat options...
And another StackOverflow post I borrowed from for adding the 6 days...
And I used this to get the correct start of the week
I have this function called week(), which gives me the current the first (startDate) and last (endDate) day of the week and the week number. I also have these two other functions called weekPlus() and weekMinus(), which contains variables that add or substract from the variables startDate / endDate by 7 and from the week number by 1.
<script>
// First and last day of the current week
var curr = new Date(new Date().getTime() + 60 * 60 * 24 * 7);
function week() {
var curr = new Date(new Date().getTime() + 60 * 60 * 24 * 7);
// First day of the week
var first = curr.getDate() - curr.getDay();
// Last day of the week
var last = first + 6;
var startDate = new Date(curr.setDate(first));
var endDate = new Date(curr.setDate(last));
document.getElementById("start").innerHTML = startDate;
document.getElementById("end").innerHTML = endDate;
// Week number
Date.prototype.getWeekNumber = function () {
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
};
document.getElementById("week").innerHTML = ("Week " + curr.getWeekNumber());
}
function weekPlus() {
// First day of the week
var first = curr.getDate() - curr.getDay();
// Last day of the week
var last = first + 6;
var startDate = new Date(curr.setDate(first + 7));
var endDate = new Date(curr.setDate(last + 7));
document.getElementById("start").innerHTML = startDate;
document.getElementById("end").innerHTML = endDate;
// Week number
Date.prototype.getWeekNumber = function () {
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
return Math.ceil((((d - yearStart) / 86400000) + 1) / 7 + 1);
};
document.getElementById("week").innerHTML = ("Week " + curr.getWeekNumber());
}
function weekMinus() {
// First day of the week
var first = curr.getDate() - curr.getDay();
// Last day of the week
var last = first + 6;
var startDate = new Date(curr.setDate(first - 7));
var endDate = new Date(curr.setDate(last - 7));
document.getElementById("start").innerHTML = startDate;
document.getElementById("end").innerHTML = endDate;
// Week number
Date.prototype.getWeekNumber = function () {
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
return Math.ceil((((d - yearStart) / 86400000) + 1) / 7 - 1);
};
document.getElementById("week").innerHTML = ("Week " + curr.getWeekNumber());
}
</script>
<div id="start">start</div>
<div id="end">end</div>
<div id="week">week</div>
<button onclick="week()">current</button>
<button onclick="weekPlus()">add</button>
<button onclick="weekMinus()">substract</button>
So the idea is that when you first click the current button you get the current date of the weeks first and last day and after that you can either add or substract to the dates.
So is there any quick and effective way to increase or decrease the days by 7 and the week number by 1 every time you click the buttons and not just once?
Problems with the code:
Adding or substracting when the month changes, month name doesn't change but stays the same, for example: Sun Oct 29 2017 19:20:14 - Wed Oct 04 2017 19:20:14
When adding or substacting, the week number sometimes jumps by 2, 5 or more.
The problem is that you're defining cur every time you call the function. If you define it outside, you can keep on adding days to the same starting date:
// First and last day of the current week
var curr = new Date(new Date().getTime() + 60 * 60 * 24 * 7);
function weekPlus()
{
// First day of the week
var first = curr.getDate() - curr.getDay();
// Last day of the week
var last = first + 6;
var startDate = new Date(curr.setDate(first + 7));
var endDate = new Date(curr.setDate(last + 7));
document.getElementById("start").innerHTML = startDate;
document.getElementById("end").innerHTML = endDate;
// Week number
Date.prototype.getWeekNumber = function () {
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
return Math.ceil((((d - yearStart) / 86400000) + 1) / 7 + 1);
};
document.getElementById("week").innerHTML = ("Week " + curr.getWeekNumber());
}
<div id="start">start</div>
<div id="end">end</div>
<div id="week">week</div>
<button onclick="weekPlus()">add</button>
You had some problems with the curr variable, since you were modifying it as you used it. Keep it as a reference and then you'll have no problems:
// First and last day of the current week
var curr = new Date(new Date().getTime() + 60 * 60 * 24 * 7);
curr.setHours(0,0,0,0);
function week() {
// First day of the week
var first = curr.getDate() - curr.getDay();
// Last day of the week
var last = first + 6;
var startDate = new Date(curr.setDate(first));
var endDate = new Date(curr.setDate(last));
document.getElementById("start").innerHTML = startDate;
document.getElementById("end").innerHTML = endDate;
// Week number
Date.prototype.getWeekNumber = function () {
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
};
document.getElementById("week").innerHTML = ("Week " + curr.getWeekNumber());
}
function startOfWeek(date) {
date.setDate(date.getDate() - date.getDay());
return date;
}
function endOfWeek(date) {
date = startOfWeek(date);
date.setDate(date.getDate() + 6);
return date;
}
function weekPlus() {
var startDate = new Date(startOfWeek(curr));
startDate.setDate(startDate.getDate() + 7);
var endDate = endOfWeek(curr);
endDate.setDate(endDate.getDate() + 7);
curr = startDate;
document.getElementById("start").innerHTML = startDate;
document.getElementById("end").innerHTML = endDate;
// Week number
Date.prototype.getWeekNumber = function () {
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
return Math.ceil((((d - yearStart) / 86400000) + 1) / 7 + 1);
};
document.getElementById("week").innerHTML = ("Week " + curr.getWeekNumber());
}
function weekMinus() {
var startDate = new Date(startOfWeek(curr));
startDate.setDate(startDate.getDate() - 7);
var endDate = endOfWeek(curr);
endDate.setDate(endDate.getDate() - 7);
curr = startDate;
document.getElementById("start").innerHTML = startDate;
document.getElementById("end").innerHTML = endDate;
// Week number
Date.prototype.getWeekNumber = function () {
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
return Math.ceil((((d - yearStart) / 86400000) + 1) / 7 - 1);
};
document.getElementById("week").innerHTML = ("Week " + curr.getWeekNumber());
}
<div id="start">start</div>
<div id="end">end</div>
<div id="week">week</div>
<button onclick="week()">current</button>
<button onclick="weekPlus()">add</button>
<button onclick="weekMinus()">substract</button>
You can move the curr variable outside of the function and every time you run the function - update the value of that variable:
// First and last day of the current week
var curr = new Date(new Date().getTime() + 60 * 60 * 24 * 7);
function weekPlus() {
// First day of the week
var first = curr.getDate() - curr.getDay();
// Last day of the week
var last = first + 6;
var startDate = new Date(curr.setDate(first + 7));
var endDate = new Date(curr.setDate(last + 7));
document.getElementById("start").innerHTML = startDate;
document.getElementById("end").innerHTML = endDate;
// Week number
Date.prototype.getWeekNumber = function () {
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
return Math.ceil((((d - yearStart) / 86400000) + 1) / 7 + 1);
};
document.getElementById("week").innerHTML = ("Week " + new Date().getWeekNumber());
curr = startDate;
}
<div id="start"></div>
<div id="end"></div>
<div id="week"></div>
<input type="button" value="Plus" id="plus" onclick="weekPlus()"/>
I create function that loop on dates and enter then to array according to the week and the day in the week.
This is the code of the loop and the functions.
var weeks = [];
//get the week number of the date;
var getWeek = function(date) {
var onejan = new Date(date.getFullYear(), 0, 1);
return Math.ceil((((date - onejan) / 86400000) + onejan.getDay() + 1) / 7);
};
var curr = new Date();
//get the first day of the week
var startDay = new Date(curr.setDate(curr.getDate() - curr.getDay()));
//endDay="2015/9/30"
var endDay = new Date(2015, 8, 30);
while (startDay < endDay) {
if (weeks[getWeek(startDay)] == undefined) {
weeks[getWeek(startDay)] = [];
}
weeks[getWeek(startDay)][startDay.getDay()] = startDay.toString();
var newDate = startDay.setDate(startDay.getDate() + 1);
startDay = new Date(newDate);
}
console.log(weeks);
The code runs and I dont know why it "confuse" with some dates but like the today 2015.9.19 it put it on month 39 but when I run the getWeek on this date it says 38.
var getWeek = function(date) {
var onejan = new Date(date.getFullYear(), 0, 1);
return Math.ceil((((date - onejan) / 86400000) + onejan.getDay() + 1) / 7);
};
alert(getWeek(new Date("2015/9/19")));
so I dont understand what is wrong in the loop.
There is nothing wrong with the loop - the problem is with how you initialize you start date. Hours, minutes and seconds in particular.
Compare these:
getWeek(new Date()); // 39
getWeek(new Date(2015, 8, 19)); // 38
getWeek(new Date(2015, 8, 19, 1)); // 39
I guess that error accumulates, when you do Math.ceil() - you might want a deeper debugging for that.
Anyway, here's how your code may look like:
var weeks = [];
//get the week number of the date;
var getWeek = function(date) {
var onejan = new Date(date.getFullYear(), 0, 1);
return Math.ceil((((date - onejan) / 86400000) + onejan.getDay() + 1) / 7);
};
var curr = new Date();
// -----------------
// Subtract the date, because there is a chance we will get a prev month.
curr.setDate(curr.getDate() - curr.getDay());
// Initialize with diff constructor, so m:h:s will be 0.
var startDay = new Date(curr.getFullYear(), curr.getMonth(), curr.getDate());
// -----------------
//endDay="2015/9/30"
var endDay = new Date(2015, 8, 30);
while (startDay < endDay) {
if (weeks[getWeek(startDay)] == undefined) {
weeks[getWeek(startDay)] = [];
}
weeks[getWeek(startDay)][startDay.getDay()] = startDay.toString();
var newDate = startDay.setDate(startDay.getDate() + 1);
startDay = new Date(newDate);
}
console.log(weeks);
I have to calculate variables in javascript after x days from current day.I have to add some number of days based on some input parameter.
var currentDate = new Date();
var dd = currentDate.getDate();
var mm = currentDate.getMonth()+1;
var yyyy = currentDate.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
currentDate= mm+'/'+dd+'/'+yyyy;
Now I want to get some date after 28 days from currentDate variable but it should not include Saturday and Sunday.
So my question is how to exclude the weekends (2 days) from the 28 (for example).
Any help will be appreciated.
Here's a generic function to add n business days to a date
function addDays(dt, n) {
var rem = n % 5;
var add = 7 * (n - rem) / 5 + rem;
var ret = new Date(dt);
ret.setDate(ret.getDate() + add);
if (ret.getDay() == 6) ret.setDate(ret.getDate() + 2);
else if (ret.getDay() == 0) ret.setDate(ret.getDate() + 1);
return ret;
}
This is really simple. Script below goes through all days between start and end date and checks if it isn't Saturday (tmpDate.getDay() != 6) or Sunday (tmpDate.getDay() != 0)
var start = new Date();
var end = new Date(2016, 6, 1);
var allDays = Math.floor((end.getTime() - start.getTime())/ 86400000);
var workingDays = 0;
for(var i = 0; i < allDays; i++){
var tmpDate = new Date();
tmpDate.setTime(today.getTime() + i * 24*60*60*1000);
if(tmpDate.getDay() != 0 && tmpDate.getDay() != 6)
wokringDays++;
}
alert(workingDays);
This will give you the number of working days:
function getWorkingDays(currentDateObj, numberOfDays)
{
if(numberOfDays < 0) return false;
var futureDateObj = new Date();
futureDateObj.setDate(currentDateObj.getDate() + numberOfDays);
var daysCnt = 1 + Math.round((futureDateObj.getTime()-currentDateObj.getTime())/(24*3600*1000));
var weekCnt = Math.floor( (currentDateObj.getDay() + daysCnt) / 7 );
var weekends = 2 * weekCnt + (currentDateObj.getDay()==0) - (futureDateObj.getDay()==6);
return numberOfDays - weekends;
}
console.log(getWorkingDays(new Date(), 28));
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
}