Javascript Date: next month

后端 未结 8 1465
情深已故
情深已故 2020-11-28 10:01

I\'ve been using Javascript\'s Date for a project, but noticed today that my code that previously worked is no longer working correctly. Instead of producing Feb as expected

8条回答
  •  被撕碎了的回忆
    2020-11-28 10:05

    I was looking for a simple one-line solution to get the next month via math so I wouldn't have to look up the javascript date functions (mental laziness on my part). Quite strangely, I didn't find one here.

    I overcame my brief bout of laziness, wrote one, and decided to share!

    Solution:

    (new Date().getMonth()+1)%12 + 1
    

    Just to be clear why this works, let me break down the magic!

    It gets the current month (which is in 0..11 format), increments by 1 for the next month, and wraps it to a boundary of 12 via modulus (11%12==11; 12%12==0). This returns the next month in the same 0..11 format, so converting to a format Date() will recognize (1..12) is easy: simply add 1 again.

    Proof of concept:

    > for(var m=0;m<=11;m++) { console.info( "next month for %i: %i", m+1, (m+1)%12 + 1 ) }
    next month for 1: 2
    next month for 2: 3
    next month for 3: 4
    next month for 4: 5
    next month for 5: 6
    next month for 6: 7
    next month for 7: 8
    next month for 8: 9
    next month for 9: 10
    next month for 10: 11
    next month for 11: 12
    next month for 12: 1
    

    So there you have it.

提交回复
热议问题