setDate(day+1) returns wrong days - javascript

Why does this:
startDate.setDate(startDate + 1);
Generates this strange order (broken at the beginning of the next month):
7, 27, 28, 30, 30, **1, 4, 3, 4, 4,** 6, 7, 10, 9, 10, 10, 12,
Update (more code):
renderWeekFromMonday : function(date) {
var dayContainer = $('#day');
// clear div
dayContainer.empty();
// Render days
for (var i = 0; i <= 7; i++) {
// Get mondday day (1-31)
var day = date.getDate();
// Today
var t = new Date();
// Create dayobject for usage inside for loop
var d = new Date(date);
// Render 7 days (1 week)
for (var i = 0; i < 7; i++) {
// New day (+1)
d.setDate(day + i)
console.info(d.getDate());
// Create html
var span = $("<span>").addClass("calElement").attr("time", d.getTime())
var w = 25;
span.html("<span class=dayNumber>" + d.getDate() + "</span><br>" + this.dayNames[d.getDay()]).css("width",w);
//span.html("<span class=dayNumber>" + d.getDate() + "</span>");
// Append day
dayContainer.append(span);
}
}
},

Just a guess, put perhaps you're looking for:
startDate.setDate(startDate.getDate() + 1);
startDate + 1 doesn't make much sense if startDate is a Date object.
After seeing updated code: Your problem is very likely in the fact that you have two nested loops, both of which increment i. Use a different variable for one of the loops.

Your code looks fine - I'm using FF4 and the date calculations look correct. I've posted the code here for a live example: http://jsfiddle.net/EbNcr/2/
Is there a specific browser or date(s) that you're testing with to get the strange results?
(I wish I could submit this as a comment, but I don't think I have the reputation for that yet...)

Thanks for helping. I just had a simple copy&paste error (two loops). I put the final code into a simple jquery plugin (inspiered by some oder plugins)
var MILLIS_IN_DAY = 86400000;
var MILLIS_IN_WEEK = MILLIS_IN_DAY * 7
jQuery.fn.calendarPicker = function(options) {
// -------------------------- start default option values --------------------------
options.date = new Date();
options.dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
options.firstDayOfWeek = 1;
options.showNavigation = true;
// -------------------------- end default option values --------------------------
var calendar = {
changeDate : function(date) {
// calculate new start date
this.currentFirstDayOfWeek = this._firstDayOfWeek(date);
// render days
for (var i = 0; i < 7; i++) {
// create dayobject
var day = new Date(this.currentFirstDayOfWeek.getTime() + MILLIS_IN_DAY * i);
// render container
var span = $("<span>").addClass("calElement").attr("time", day.getTime())
// render day
span.html("<span class=dayNumber>" + day.getDate() + "</span><br>" + options.dayNames[day.getDay()]);
if (day.getYear() == date.getYear() && date.getMonth() == day.getMonth() && day.getDate() == date.getDate())
span.addClass("today");
if (day.getYear() == date.getYear() && day.getMonth() == date.getMonth() && day.getDate() == date.getDate())
span.addClass("selected");
theDiv.append(span);
// render navigation
if (i == 0 && options.showNavigation) {
var prevBtn = $("<span>").addClass("prev").html("prev");
var self = this;
prevBtn.bind('click', function() { self.prevWeek(); });
theDiv.prepend(prevBtn);
} else if (i == 6 && options.showNavigation) {
var nextBtn = $("<span>").addClass("next").html("next")
var self = this;
nextBtn.bind('click', function() { self.nextWeek(); });
theDiv.append(nextBtn);
}
}
},
/*
* Go to the previous week relative to the currently displayed week
*/
prevWeek : function() {
//minus more than 1 day to be sure we're in previous week - account for daylight savings or other anomolies
var newDate = new Date(this.currentFirstDayOfWeek.getTime() - (MILLIS_IN_WEEK / 6));
this._clearCalendar();
this.changeDate(newDate);
},
/*
* Go to the next week relative to the currently displayed week
*/
nextWeek : function() {
//add 8 days to be sure of being in prev week - allows for daylight savings or other anomolies
var newDate = new Date(this.currentFirstDayOfWeek.getTime() + MILLIS_IN_WEEK + (MILLIS_IN_WEEK / 7));
this._clearCalendar();
this.changeDate(newDate);
},
/*
* returns the date on the first millisecond of the week
*/
_firstDayOfWeek : function(date) {
var midnightCurrentDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var adjustedDate = new Date(midnightCurrentDate);
adjustedDate.setDate(adjustedDate.getDate() - this._getAdjustedDayIndex(midnightCurrentDate));
return adjustedDate;
},
_clearCalendar : function() {
theDiv.empty();
},
/*
* gets the index of the current day adjusted based on options (e.g.firstDayofWeek)
*/
_getAdjustedDayIndex : function(date) {
var midnightCurrentDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var currentDayOfStandardWeek = midnightCurrentDate.getDay();
var days = [0,1,2,3,4,5,6];
this._rotate(days, this.options.firstDayOfWeek);
return days[currentDayOfStandardWeek];
},
/*
* rotate an array by specified number of places.
*/
_rotate : function(a, p ) {
for (var l = a.length, p = (Math.abs(p) >= l && (p %= l),p < 0 && (p += l),p), i, x; p; p = (Math.ceil(l / p) - 1) * p - l + (l = p)) {
for (i = l; i > p; x = a[--i],a[i] = a[i - p],a[i - p] = x);
}
return a;
},
};
// Pass options
calendar.options = options;
// build the calendar on the first element in the set of matched elements.
var theDiv = this.eq(0);//$(this);
theDiv.addClass("calBox");
// empty the div
theDiv.empty();
// entry point
calendar.changeDate(options.date);
return calendar;
};

Related

create array of array of datepairs that have gap of n days between them

Consider 2 dates, format will be MM/DD/YYYY
1st date = today
2nd date = 45 days from today
Note: Here, the 1st date and 2nd date are variable.
i.e. 1st date that is today can be tomorrow or any other date. 2nd date can be 15 days, 24 days, 105 days i.e. this "n" can also vary.
Assuming the above 2 dates as startDate and stopDate. I want to create array of datePairs of a given gap between them.
For e.g. if startDate = 12/01/2022 & stopDate = 12/20/2022. I want to have datePairs having gap of 2 (n = 2) days between them. So, the output array should look like
[
['12/01/2022', '12/03/2022'],
['12/04/2022', '12/06/2022'],
['12/07/2022', '12/09/2022'],
['12/10/2022', '12/12/2022'],
['12/13/2022', '12/15/2022'],
['12/16/2022', '12/18/2022'],
['12/19/2022', '12/20/2022']
]
NOTE: Here, the last array does not have the gap of 2 dates because it's just 1 day away from the stopDate. In such case, the last pair can have less gap between them.
The only condition is the above array length should always be even.
Date.prototype.addDays = function (days) {
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
};
function splitInto(array, size, inplace) {
var output, i, group;
if (inplace) {
output = array;
for (i = 0; i < array.length; i++) {
group = array.splice(i, size);
output.splice(i, 0, group);
}
} else {
output = [];
for (i = 0; i < array.length; i += size) {
output.push(array.slice(i, size + i));
}
}
return output;
}
function getDates(startDate, stopDate) {
var dateArray = new Array();
var currentDate = startDate;
var i = 0;
while (currentDate <= stopDate) {
if (i % 2 == 1) {
const options = {
year: 'numeric'
};
options.month = options.day = '2-digit';
var formattedCSTDate = new Intl.DateTimeFormat([], options).format(currentDate);
dateArray.push(formattedCSTDate);
currentDate = currentDate.addDays(1);
} else {
const options = {
year: 'numeric'
};
options.month = options.day = '2-digit';
var formattedCSTDate = new Intl.DateTimeFormat([], options).format(currentDate);
dateArray.push(formattedCSTDate);
currentDate = currentDate.addDays(3);
}
i = i + 1;
}
return dateArray;
};
var dateArray = getDates(new Date(), (new Date()).addDays(43));
var datePairLength = 2;
var rangeArray = splitInto(dateArray, datePairLength, false);
console.log(rangeArray);
It seems to me you're making it more complicated than it needs to be. Just build each range as an array and avoid the splitInto function. You might use a date library (there are many to chose from) for adding days and formatting:
function makeRanges(start = new Date(), end = new Date(), interval = 1) {
let f = new Intl.DateTimeFormat('default', {
year:'numeric',month:'short',day:'2-digit'
});
let s = new Date(start);
let ranges = [];
while (s < end) {
let t = new Date(s);
t.setDate(t.getDate() + interval);
ranges.push([f.format(s), t < end? f.format(t) : f.format(end)]);
s.setDate(s.getDate() + interval + 1)
}
return ranges;
}
console.log(
makeRanges(new Date(2022,0,1), new Date(2022,1,1), 2)
);

get last 7 days when user picks up a date

I have a datetimepicker where the user picks up a date, and my requirement is I need 7 days difference between his selected date.
For eg,
if user has selected 2017-03-01 so i need last 7 days from 2017-03-01 and NOT the current date
All answers i checked here were based on days difference from today.
Can anyone help me out here ?
$("#dateTimePickerIdWhereUserSelectsHisDate").val() - (7 * 24 * 60 * 60 * 1000);
this was on one of the answers but didn't work.
How can I achieve this ?
Try This
SelectDateTime will give you selected date
604800000 is 7 days in miliseconds
prevDate will give you last 7 days Date
$("#startDate").on("dp.change", function(e) {
if (e.oldDate != null) {
if (e.date.format('D') != e.oldDate.format('D')) {
var selectDateTime = e.date["_d"].getTime();
var prevDateTImeMili = selectDateTime - 604800000;
var prevDate = msToDateTime(prevDateTImeMili)
$('#startDate').data("DateTimePicker").hide();
}
}
});
msToDateTime is a function which converts milliseconds to DateTime
function msToDateTime(s) {
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
if(s != null){
s = new Date(s);
// var d = new Date(s);
// var d = new Date(s.getTime()+s.getTimezoneOffset()*60*1000+timeConversionToMilliseconds(sessionStorage.getItem("accounttimezone").split('+')[1]+':00'))
var d = new Date(s.getTime()+(s.getTimezoneOffset()*60*1000)+ (330 *60*1000));
dformat = [ d.getFullYear(),
(d.getMonth()+1).padLeft(),
d.getDate().padLeft()].join('-')+
' ' +
[ d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
return dformat;
}else{
return " ";
}
}
function getNDaysBefore(dateString, numberOfDaysBefore) {
let startingDate = new Date(dateString).getTime();
let datesArray = [],
daysCounter = 0,
day = 1000 * 60 * 60 * 24;
while (daysCounter < numberOfDaysBefore + 1) {
let newDateBeforeStaring = startingDate - day * daysCounter;
datesArray.push(new Date(newDateBeforeStaring));
daysCounter++;
}
return datesArray;
}
var dateString = "2016-03-01";
alert(getNDaysBefore(dateString,7));
With that kind of a function you can get any N days before the given date as an array of Date objects

Get only number of working days between two days in javascript

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

date error for date class google appscript

The problem that i am having here is that when i minus back to then end of the month, instead of going back to the 29 or 28 of last month the program starts to minus months instead of days. Bellow is my full code and below that is the output it produces in the google spread sheet.
function trying(){
var date = new Date();
var datechange = new Date();
var array = new Array(7);
for (var i = 0; i < 7; i++) {
array[i] = new Array(0);
}
for ( var i = 0; i < 7; i++){
days = i + 8
datechange.setDate(date.getDate() - days);
var tabName = Utilities.formatDate(datechange, 'MST', 'yyyy-MM-dd').toString();
array[i][0] = tabName;
}
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Want");
sheet.getRange("B2:B8").setValues(array);
}
This are the dates that are produced.
05/07/2012
04/07/2012
03/07/2012
02/07/2012
01/07/2012
30/06/2012
30/05/2012
You have to define datechange inside your loop, and not outside:
var date = new Date();
for ( var i = 0; i < 30; i++){
days = i + 8
var datechange = new Date();
datechange.setDate(date.getDate() - i);
console.log(datechange);
}
Date.getDate() returns the date (1-31) - so what you are doing is not correct.
Instead try this:
var ONE_DAY = 24 * 60 * 60 * 1000; //in milliseconds
for ( var i = 0; i < 7; i++){
days = i + 8
datechange.setDate(date.getTime() - (days * ONE_DAY));
var tabName = Utilities.formatDate(datechange, 'MST', 'yyyy-MM-dd').toString();
array[i][0] = tabName;
}
This is how JavaScript dates work. See here for full details.

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