As shown in the figure, the js code today is 31 July. Why does typing "- 1" return July 1st instead of June 30?

function getMonthAfter (num){
    var dt = new Date();
    dt.setMonth( dt.getMonth()+num );
    return dt.toLocaleString()
}

now that you know where the problem lies, how should you deal with it?

Apr.01,2021

because the Date object of js handles the overflow time on its own.
Today is July 31 you Month-1 gets June 31
but June does not have 31, and the extra day is automatically added to become July 1
you can try dt.setMonth (1) to February, and you will find that the result is March 3
or set to a number that exceeds the maximum date of the month. For example, dt.setDate (35) the result is August 4th
it's all because of this automatic processing algorithm


a logical process. July 31 separates month from day,. After you set month-1, separately, 31 will be calculated as June 31 = > July 1


probably because there is no 31 in June

.
Menu