美文网首页
JS date setMonth 的问题

JS date setMonth 的问题

作者: avery1 | 来源:发表于2023-03-29 10:11 被阅读0次

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth

    来看MDN的说明

    The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days.

    这里已经说明了,setMonth的时候会把当前的date应用到目标的month, 如果date超出目标月份的日期,可能就会到下个月了。举个例子

    当前是2023-03-30

    如果new Date()  之后setMonth(date.getMonth() - 1) 也就是上个月,实际上结果会变成 2023-03-02, 因为set完之后变成2023-02-30, 实际2月28天就到了03-02

    let date = new Date();

    date.setMonth(date.getMonth() - 1)

    相关文章

      网友评论

          本文标题:JS date setMonth 的问题

          本文链接:https://www.haomeiwen.com/subject/iycfddtx.html