简体   繁体   English

当获得一个月的总周数时的奇怪行为

[英]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: 控制台日志: 在此处输入图片说明

HTML code HTML代码

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

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). 问题在于,使用date.setDate(1)表达式可以更改原始日期对象(作为参数传递给此函数)。 Obviously, that's not what you want. 显然,这不是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM