Date Calculation Error

I have below calculation:

vCurrDate = new Date();
vDueFromDate = new Date();
vDueToDate = new Date();    
vOverDueToDate = new Date();
vCurrDate.setDate(vCurrDate.getDate() - 1);
vDueFromDate.setDate(vCurrDate.getDate() - 30);
vDueToDate.setDate(vCurrDate.getDate());
vOverDueToDate.setDate(vCurrDate.getDate() - 31);

On March 02 2018 (today), all the above calculations are working fine. But, on March 01 2018, last three calculations went wrong. Below shows the result of above calculations with both mentioned dates:

--On March 02 2018 (today)

Thu Mar 01 2018 12:03:34 GMT+0530 (India Standard Time) **** 01-Mar-2018

Tue Jan 30 2018 12:03:34 GMT+0530 (India Standard Time) **** 30-Jan-2018

Thu Mar 01 2018 12:03:34 GMT+0530 (India Standard Time) **** 01-Mar-2018

Mon Jan 29 2018 12:03:34 GMT+0530 (India Standard Time) **** 29-Jan-2018

--On March 01 2018 (yesterday)

Wed Feb 28 2018 12:12:32 GMT+0530 (India Standard Time) **** 28-Feb-2018

Mon Feb 26 2018 12:12:32 GMT+0530 (India Standard Time) **** instead of 29-jan-2018

Wed Mar 28 2018 12:12:32 GMT+0530 (India Standard Time) **** 28-Feb-2018

Sun Feb 25 2018 12:12:32 GMT+0530 (India Standard Time) **** 28-jan-2018


Hmmm....Look. From documentation we now about .setDate(..) next:

If the dayValue is outside of the range of date values for the month, setDate() will update the Date object accordingly. For example, if 0 is provided for dayValue, the date will be set to the last day of the previous month.

Let's understand what happens with your date on March 1st.

vCurrDate.setDate(vCurrDate.getDate() - 1);

After that vCurrDate assigned to 28th of February according to setDate specification

vDueFromDate.setDate(vCurrDate.getDate() - 30);

To vDueFromDate you set date as 28-30 or -2 days from current date. 0 means last day of previous months, so -2 is a 26th of February

vDueToDate.setDate(vCurrDate.getDate());

As mentioned above vCurrDate.getDate() now is 28 , so we set vDueToDate to 28th of current month, ie 28th of March.

vOverDueToDate.setDate(vCurrDate.getDate() - 31);

In this case you tried to set date to -3 of current month, so, as it mentioned above, this is 25th of Feb

链接地址: http://www.djcxy.com/p/46598.html

上一篇: 创建javascript Date()对象到Amrica / New

下一篇: 日期计算错误