imdadhusen
imdadhusen

Reputation: 2494

Strange behavior when getting total weeks of the month

I have strange problem. I have to calculate total weeks of the given date month.

My logic is working perfectly it will return me correct week number but the problem is my original date was also getting changed during calculating weeks.

I have stored my original date in other variable and passed other variable to the function but still the original date is also getting changed. How can i restrict change my original date?

 var currentDate;
 $(document).ready(function () {
    currentDate = new Date();
 });
function goNextMonth() {
   var dt = currentDate;
   console.log("Before Date: " + currentDate);
   var weeks = getWeeksOfMonth(dt);
   console.log("After Date: " + currentDate + ", Weeks: " + weeks);
}
function getWeeksOfMonth(date) {
    var firstDay = new Date(date.setDate(1)).getDay();
    var totalDays = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
    return Math.ceil((firstDay + totalDays) / 7);
}

Cosole Log: enter image description here

HTML code

 <input type="button" value="Next Month" onclick="goNextMonth()" />

Upvotes: 1

Views: 91

Answers (1)

raina77ow
raina77ow

Reputation: 106443

Turn this line...

var firstDay = new Date(date.setDate(1)).getDay();

... into this:

var dateClone = new Date(date);
dateClone.setDate(1);
var firstDay = dateClone.getDay();

The problem is that with date.setDate(1) expression you change the original date object (passed into this function as a param). Obviously, that's not what you want.

Upvotes: 2

Related Questions